How to Cache Dependencies in GitLab CI
GitLab CI caches directories declared under cache.paths, keyed by cache.key, with policy choosing pull, push, or both.
Add a cache: block with key, paths, and optionally policy. Use key.files to hash a lockfile so the cache changes with dependencies, and set policy: pull on jobs that only read the cache to avoid re-uploading it.
Steps
- List the directories to cache under
cache.paths. - Key on a lockfile with
cache.key.files. - Set
policy: pullon read-only consumers.
Pipeline
.gitlab-ci.yml
build:
stage: build
cache:
key:
files:
- package-lock.json
paths:
- .npm/
policy: pull-push
script:
- npm ci --cache .npm --prefer-offlineGotchas
- Cache is best-effort and tied to the runner or your object storage, unlike stricter artifacts.
- Use
policy: pullin test jobs so only the build job uploads the cache.
Related guides
How to Handle Caching on Self-Hosted RunnersUnderstand how actions/cache behaves on self-hosted GitHub Actions runners, and when a persistent local tool…
How to Use the Built-in cache Input of setup-nodeEnable dependency caching with one line using the cache input of actions/setup-node, which auto-detects your…