Maven Mirror

Maven mirrors allow you to redirect requests to remote repositories to an alternative repository or server. This is useful when you want to optimize build times by redirecting to a local or nearby mirror or when you need to enforce usage of an internal repository within an organization.

This tutorial will guide you through setting up a Maven mirror.

Prerequisites:

  • Maven installed and configured on your system.
  • Access to the mirror repository (local or remote).

Steps to Configure a Maven Mirror:

  • Locate Maven's settings file:

Maven's settings file, "settings.xml," is located in the Maven's installation directory under the "conf" folder (i.e., ${MAVEN_HOME}/conf/settings.xml).

Alternatively, you can create a user-specific "settings.xml" file in your home directory under the .m2 folder (i.e., ~/.m2/settings.xml on macOS/Linux or %USERPROFILE%\.m2\settings.xml on Windows).

If the user-specific settings file does not exist, create it by copying the default one from the Maven installation directory.

  • Edit the "settings.xml" file:

Open the "settings.xml" file in a text editor. Locate the <mirrors> element. If it does not exist, add it inside the <settings> element.

  • Add the mirror configuration:

Add a <mirror> element inside the <mirrors> element with the following structure:

<mirror>
  <id>my-mirror</id>
  <url>http://my-mirror.example.com</url>
  <mirrorOf>*</mirrorOf>
</mirror>

Replace the following:

  • my-mirror: A unique identifier for the mirror.
  • http://my-mirror.example.com: The URL of the mirror repository.
  • *: A comma-separated list of repositories to be mirrored. Use * to mirror all repositories, or provide specific repository IDs (e.g., central,other-repo).

Here's an example that mirrors Maven Central to a local Nexus repository:

<mirror>
  <id>nexus-local</id>
  <url>http://localhost:8081/repository/maven-central/</url>
  <mirrorOf>central</mirrorOf>
</mirror>
  • Save and close the "settings.xml" file:

Save the changes and close the text editor.

  • Test the mirror configuration:

Run a Maven command that fetches dependencies (e.g., mvn clean install). Maven should use the mirror repository to download dependencies instead of the original repositories.

In conclusion, configuring a Maven mirror allows you to redirect requests to remote repositories, optimizing build times and enforcing usage of specific repositories. This is particularly useful for organizations with internal repositories or local mirrors.