Skip to content
Latchkey

How to Cache Maven .m2 in GitHub Actions

Maven downloads its entire dependency tree from scratch on a fresh runner unless the local repo is cached.

Use actions/setup-java with built-in Maven caching, or cache ~/.m2/repository directly keyed on pom.xml.

Steps

  • Add actions/setup-java and set cache: maven for the simplest path.
  • Or add an explicit actions/cache step over ~/.m2/repository.
  • Key on hashFiles(**/pom.xml) with a restore-keys fallback.
  • Run mvn -B verify so the cache populates on first use.

Workflow

.github/workflows/maven.yml
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '21'
          cache: maven
      - run: mvn -B verify

Gotchas

  • Avoid caching -SNAPSHOT artifacts you publish locally; they go stale and mask real failures.
  • Use -B (batch mode) to keep logs clean and downloads deterministic.
  • Latchkey keeps the Maven repository warm between runs so builds are cheaper and self-healing.

Related guides

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