Skip to content
Latchkey

How to Cache Maven Dependencies in GitLab CI

Point Maven at a project-local .m2 directory and let GitLab cache it between jobs.

Maven downloads to ~/.m2 by default, which GitLab cannot cache. Override the local repository into the project tree, then cache that path keyed on pom.xml so the cache invalidates only when dependencies change.

Cache .m2 keyed on pom.xml

Set maven.repo.local under the workspace, then declare a cache keyed on the pom file checksum.

.gitlab-ci.yml
variables:
  MAVEN_OPTS: "-Dmaven.repo.local=${CI_PROJECT_DIR}/.m2/repository"

build:
  image: maven:3.9-eclipse-temurin-21
  cache:
    key:
      files:
        - pom.xml
    paths:
      - .m2/repository
  script:
    - mvn -B verify

Notes

  • The files: key recomputes the cache key only when pom.xml changes, so most pipelines hit a warm cache.
  • Use -B (batch mode) to keep logs clean and avoid interactive prompts.
  • Teams that want zero cache plumbing can migrate to GitHub Actions on Latchkey managed runners, where dependency caching is handled for you.

Verify it actually works

Terminal
# validate the pipeline definition against your project's CI lint
curl -s --header "PRIVATE-TOKEN: $TOKEN" \
  "https://gitlab.com/api/v4/projects/$PROJECT_ID/ci/lint" \
  --data-urlencode "content=$(cat .gitlab-ci.yml)"

# then confirm which rules matched on a real pipeline
# CI/CD -> Pipelines -> the run -> each job -> "Trigger"

Frequently asked questions

How do I cache Maven Dependencies in GitLab CI?
Maven downloads to ~/.m2 by default, which GitLab cannot cache. Override the local repository into the project tree, then cache that path keyed on pom.xml so the cache invalidates only when dependencies change.
Cache .m2 keyed on pom.xml?
Set maven.repo.local under the workspace, then declare a cache keyed on the pom file checksum.

Related guides

References

Run this faster and cheaper on Latchkey managed runners - self-healing included. Start free → 30-day trial · No credit card