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 verifyNotes
- 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
How to Run a Job Manually with Input Variables in GitLab CITrigger a GitLab CI job by hand and let the operator supply values using a manual when:manual job plus pre-fi…
How to Publish a Docker Image to the GitLab Registry in GitLab CIBuild and push a container image to the GitLab Container Registry from CI using the built-in CI_REGISTRY cred…