Skip to content
Latchkey

How to Cache the Maven .m2 Repository in CI

A cold Maven build pulls a deep tree of JARs from Maven Central. Caching the local .m2 repository turns minutes of downloads into a restore.

Maven stores every downloaded artifact under ~/.m2/repository. Restore that directory keyed on your pom files and the build stops re-fetching the same dependencies on every run.

1. Use the built-in setup-java cache

setup-java caches ~/.m2/repository keyed on pom.xml when you pass cache: maven.

.github/workflows/ci.yml
- uses: actions/setup-java@v4
  with:
    distribution: temurin
    java-version: '21'
    cache: maven
- run: mvn -B -ntp verify

2. Or cache it manually with a tighter key

A manual cache lets you key on every pom in a multi-module build.

.github/workflows/ci.yml
- uses: actions/cache@v4
  with:
    path: ~/.m2/repository
    key: m2-${{ hashFiles('**/pom.xml') }}
    restore-keys: m2-

3. Do not cache the whole ~/.m2

Cache only repository. The ~/.m2/settings.xml may carry credentials and the wrapper dir changes rarely; caching the repository alone keeps the artifact clean.

4. Pair with offline mode for determinism

After a warm cache, mvn -o (offline) proves the cache is complete and stops accidental network fetches from slowing or flaking the build.

Key takeaways

  • Cache ~/.m2/repository keyed on your pom files, not the whole ~/.m2.
  • setup-java cache: maven is the simplest correct option.
  • Use offline mode to verify the cache is complete and avoid surprise fetches.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →