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.

Related guides

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