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.
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
How to Cancel Redundant Pipelines in GitLab CICancel redundant GitLab CI pipelines with interruptible jobs plus auto-cancel redundant pipelines, and use
How to Retry a Failing Job in GitLab CIAutomatically retry a failing GitLab CI job with the retry keyword - set max attempts and scope retries to
How to Set a Job Timeout in GitLab CISet a job timeout in GitLab CI with the timeout keyword, how it interacts with the project and runner