summaryrefslogtreecommitdiff
path: root/doc/ci/caching/index.md
blob: d7c5b089116f30e107799cd0e21d5fd1a5953de4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
---

# Caching in GitLab CI/CD **(FREE)**

A cache is one or more files a job downloads and saves. Subsequent jobs that use
the same cache don't have to download the files again, so they execute more quickly.

To learn how to define the cache in your `.gitlab-ci.yml` file,
see the [`cache` reference](../yaml/index.md#cache).

## How cache is different from artifacts

Use cache for dependencies, like packages you download from the internet.
Cache is stored where GitLab Runner is installed and uploaded to S3 if
[distributed cache is enabled](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching).

Use artifacts to pass intermediate build results between stages.
Artifacts are generated by a job, stored in GitLab, and can be downloaded.

Both artifacts and caches define their paths relative to the project directory, and
can't link to files outside it.

### Cache

- Define cache per job by using the `cache` keyword. Otherwise it is disabled.
- Subsequent pipelines can use the cache.
- Subsequent jobs in the same pipeline can use the cache, if the dependencies are identical.
- Different projects cannot share the cache.
- By default, protected and non-protected branches [do not share the cache](#cache-key-names). However, you can [change this behavior](#use-the-same-cache-for-all-branches).

### Artifacts

- Define artifacts per job.
- Subsequent jobs in later stages of the same pipeline can use artifacts.
- Different projects cannot share artifacts.
- Artifacts expire after 30 days by default. You can define a custom [expiration time](../yaml/index.md#artifactsexpire_in).
- The latest artifacts do not expire if [keep latest artifacts](../pipelines/job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs) is enabled.
- Use [dependencies](../yaml/index.md#dependencies) to control which jobs fetch the artifacts.

## Good caching practices

To ensure maximum availability of the cache, do one or more of the following:

- [Tag your runners](../runners/configure_runners.md#use-tags-to-control-which-jobs-a-runner-can-run) and use the tag on jobs
  that share the cache.
- [Use runners that are only available to a particular project](../runners/runners_scope.md#prevent-a-project-runner-from-being-enabled-for-other-projects).
- [Use a `key`](../yaml/index.md#cachekey) that fits your workflow. For example,
  you can configure a different cache for each branch.

For runners to work with caches efficiently, you must do one of the following:

- Use a single runner for all your jobs.
- Use multiple runners that have
  [distributed caching](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching),
  where the cache is stored in S3 buckets. Shared runners on GitLab.com behave this way. These runners can be in autoscale mode,
  but they don't have to be.
- Use multiple runners with the same architecture and have these runners
  share a common network-mounted directory to store the cache. This directory should use NFS or something similar.
  These runners must be in autoscale mode.

## Use multiple caches

> - [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/32814) in GitLab 13.10.
> - [Feature Flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/321877), in GitLab 13.12.

You can have a maximum of four caches:

```yaml
test-job:
  stage: build
  cache:
    - key:
        files:
          - Gemfile.lock
      paths:
        - vendor/ruby
    - key:
        files:
          - yarn.lock
      paths:
        - .yarn-cache/
  script:
    - bundle config set --local path 'vendor/ruby'
    - bundle install
    - yarn install --cache-folder .yarn-cache
    - echo Run tests...
```

If multiple caches are combined with a fallback cache key,
the fallback cache is fetched every time a cache is not found.

## Use a fallback cache key

> [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/1534) in GitLab Runner 13.4.

You can use the `$CI_COMMIT_REF_SLUG` [predefined variable](../variables/predefined_variables.md)
to specify your [`cache:key`](../yaml/index.md#cachekey). For example, if your
`$CI_COMMIT_REF_SLUG` is `test`, you can set a job to download cache that's tagged with `test`.

If a cache with this tag is not found, you can use `CACHE_FALLBACK_KEY` to
specify a cache to use when none exists.

In the following example, if the `$CI_COMMIT_REF_SLUG` is not found, the job uses the key defined
by the `CACHE_FALLBACK_KEY` variable:

```yaml
variables:
  CACHE_FALLBACK_KEY: fallback-key

job1:
  script:
    - echo
  cache:
    key: "$CI_COMMIT_REF_SLUG"
    paths:
      - binaries/
```

## Disable cache for specific jobs

If you define the cache globally, each job uses the
same definition. You can override this behavior for each job.

To disable it completely for a job, use an empty hash:

```yaml
job:
  cache: []
```

## Inherit global configuration, but override specific settings per job

You can override cache settings without overwriting the global cache by using
[anchors](../yaml/yaml_optimization.md#anchors). For example, if you want to override the
`policy` for one job:

```yaml
default:
  cache: &global_cache
    key: $CI_COMMIT_REF_SLUG
    paths:
      - node_modules/
      - public/
      - vendor/
    policy: pull-push

job:
  cache:
    # inherit all global cache settings
    <<: *global_cache
    # override the policy
    policy: pull
```

For more information, see [`cache: policy`](../yaml/index.md#cachepolicy).

## Common use cases for caches

Usually you use caches to avoid downloading content, like dependencies
or libraries, each time you run a job. Node.js packages,
PHP packages, Ruby gems, Python libraries, and others can be cached.

For examples, see the [GitLab CI/CD templates](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).

### Share caches between jobs in the same branch

To have jobs in each branch use the same cache, define a cache with the `key: $CI_COMMIT_REF_SLUG`:

```yaml
cache:
  key: $CI_COMMIT_REF_SLUG
```

This configuration prevents you from accidentally overwriting the cache. However, the
first pipeline for a merge request is slow. The next time a commit is pushed to the branch, the
cache is re-used and jobs run faster.

To enable per-job and per-branch caching:

```yaml
cache:
  key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
```

To enable per-stage and per-branch caching:

```yaml
cache:
  key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
```

### Share caches across jobs in different branches

To share a cache across all branches and all jobs, use the same key for everything:

```yaml
cache:
  key: one-key-to-rule-them-all
```

To share a cache between branches, but have a unique cache for each job:

```yaml
cache:
  key: $CI_JOB_NAME
```

### Cache Node.js dependencies

If your project uses [npm](https://www.npmjs.com/) to install Node.js
dependencies, the following example defines `cache` globally so that all jobs inherit it.
By default, npm stores cache data in the home folder (`~/.npm`). However, you
[can't cache things outside of the project directory](../yaml/index.md#cachepaths).
Instead, tell npm to use `./.npm`, and cache it per-branch:

```yaml
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Nodejs.gitlab-ci.yml
#
image: node:latest

# Cache modules in between jobs
cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - .npm/

before_script:
  - npm ci --cache .npm --prefer-offline

test_async:
  script:
    - node ./specs/start.js ./specs/async.spec.js
```

#### Compute the cache key from the lock file

You can use [`cache:key:files`](../yaml/index.md#cachekeyfiles) to compute the cache
key from a lock file like `package-lock.json` or `yarn.lock`, and reuse it in many jobs.

```yaml
# Cache modules using lock file
cache:
  key:
    files:
      - package-lock.json
  paths:
    - .npm/
```

If you're using [Yarn](https://yarnpkg.com/), you can use [`yarn-offline-mirror`](https://classic.yarnpkg.com/blog/2016/11/24/offline-mirror/)
to cache the zipped `node_modules` tarballs. The cache generates more quickly, because
fewer files have to be compressed:

```yaml
job:
  script:
    - echo 'yarn-offline-mirror ".yarn-cache/"' >> .yarnrc
    - echo 'yarn-offline-mirror-pruning true' >> .yarnrc
    - yarn install --frozen-lockfile --no-progress
  cache:
    key:
      files:
        - yarn.lock
    paths:
      - .yarn-cache/
```

### Cache PHP dependencies

If your project uses [Composer](https://getcomposer.org/) to install
PHP dependencies, the following example defines `cache` globally so that
all jobs inherit it. PHP libraries modules are installed in `vendor/` and
are cached per-branch:

```yaml
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/PHP.gitlab-ci.yml
#
image: php:7.2

# Cache libraries in between jobs
cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - vendor/

before_script:
  # Install and run Composer
  - curl --show-error --silent "https://getcomposer.org/installer" | php
  - php composer.phar install

test:
  script:
    - vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never
```

### Cache Python dependencies

If your project uses [pip](https://pip.pypa.io/en/stable/) to install
Python dependencies, the following example defines `cache` globally so that
all jobs inherit it. pip's cache is defined under `.cache/pip/` and is cached per-branch:

```yaml
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml
#
image: python:latest

# Change pip's cache directory to be inside the project directory since we can
# only cache local items.
variables:
  PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"

# Pip's cache doesn't store the python packages
# https://pip.pypa.io/en/stable/reference/pip_install/#caching
cache:
  paths:
    - .cache/pip

before_script:
  - python -V               # Print out python version for debugging
  - pip install virtualenv
  - virtualenv venv
  - source venv/bin/activate

test:
  script:
    - python setup.py test
    - pip install flake8
    - flake8 .
```

### Cache Ruby dependencies

If your project uses [Bundler](https://bundler.io) to install
gem dependencies, the following example defines `cache` globally so that all
jobs inherit it. Gems are installed in `vendor/ruby/` and are cached per-branch:

```yaml
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Ruby.gitlab-ci.yml
#
image: ruby:2.6

# Cache gems in between builds
cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - vendor/ruby

before_script:
  - ruby -v                                        # Print out ruby version for debugging
  - bundle config set --local path 'vendor/ruby'   # The location to install the specified gems to
  - bundle install -j $(nproc)                     # Install dependencies into ./vendor/ruby

rspec:
  script:
    - rspec spec
```

If you have jobs that need different gems, use the `prefix`
keyword in the global `cache` definition. This configuration generates a different
cache for each job.

For example, a testing job might not need the same gems as a job that deploys to
production:

```yaml
cache:
  key:
    files:
      - Gemfile.lock
    prefix: $CI_JOB_NAME
  paths:
    - vendor/ruby

test_job:
  stage: test
  before_script:
    - bundle config set --local path 'vendor/ruby'
    - bundle install --without production
  script:
    - bundle exec rspec

deploy_job:
  stage: production
  before_script:
    - bundle config set --local path 'vendor/ruby'   # The location to install the specified gems to
    - bundle install --without test
  script:
    - bundle exec deploy
```

### Cache Go dependencies

If your project uses [Go Modules](https://github.com/golang/go/wiki/Modules) to install
Go dependencies, the following example defines `cache` in a `go-cache` template, that
any job can extend. Go modules are installed in `${GOPATH}/pkg/mod/` and
are cached for all of the `go` projects:

```yaml
.go-cache:
  variables:
    GOPATH: $CI_PROJECT_DIR/.go
  before_script:
    - mkdir -p .go
  cache:
    paths:
      - .go/pkg/mod/

test:
  image: golang:1.13
  extends: .go-cache
  script:
    - go test ./... -v -short
```

## Availability of the cache

Caching is an optimization, but it isn't guaranteed to always work. You might need
to regenerate cached files in each job that needs them.

After you define a [cache in `.gitlab-ci.yml`](../yaml/index.md#cache),
the availability of the cache depends on:

- The runner's executor type.
- Whether different runners are used to pass the cache between jobs.

### Where the caches are stored

All caches defined for a job are archived in a single `cache.zip` file.
The runner configuration defines where the file is stored. By default, the cache
is stored on the machine where GitLab Runner is installed. The location also depends on the type of executor.

| Runner executor        | Default path of the cache |
| ---------------------- | ------------------------- |
| [Shell](https://docs.gitlab.com/runner/executors/shell.html) | Locally, under the `gitlab-runner` user's home directory: `/home/gitlab-runner/cache/<user>/<project>/<cache-key>/cache.zip`. |
| [Docker](https://docs.gitlab.com/runner/executors/docker.html) | Locally, under [Docker volumes](https://docs.gitlab.com/runner/executors/docker.html#the-builds-and-cache-storage): `/var/lib/docker/volumes/<volume-id>/_data/<user>/<project>/<cache-key>/cache.zip`. |
| [Docker Machine](https://docs.gitlab.com/runner/executors/docker_machine.html) (autoscale runners) | The same as the Docker executor. |

If you use cache and artifacts to store the same path in your jobs, the cache might
be overwritten because caches are restored before artifacts.

#### Cache key names

> [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/330047) in GitLab 15.0.

A suffix is added to the cache key, with the exception of the [fallback cache key](#use-a-fallback-cache-key).

As an example, assuming that `cache.key` is set to `$CI_COMMIT_REF_SLUG`, and that we have two branches `main`
and `feature`, then the following table represents the resulting cache keys:

| Branch name | Cache key |
|-------------|-----------|
| `main`      | `main-protected` |
| `feature`   | `feature-non_protected` |

##### Use the same cache for all branches

> [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/361643) in GitLab 15.0.

If you do not want to use [cache key names](#cache-key-names),
you can have all branches (protected and unprotected) use the same cache.

The cache separation with [cache key names](#cache-key-names) is a security feature
and should only be disabled in an environment where all users with Developer role are highly trusted.

To use the same cache for all branches:

1. On the top bar, select **Main menu > Projects** and find your project.
1. On the left sidebar, select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Clear the **Use separate caches for protected branches** checkbox.
1. Select **Save changes**.

### How archiving and extracting works

This example shows two jobs in two consecutive stages:

```yaml
stages:
  - build
  - test

before_script:
  - echo "Hello"

job A:
  stage: build
  script:
    - mkdir vendor/
    - echo "build" > vendor/hello.txt
  cache:
    key: build-cache
    paths:
      - vendor/
  after_script:
    - echo "World"

job B:
  stage: test
  script:
    - cat vendor/hello.txt
  cache:
    key: build-cache
    paths:
      - vendor/
```

If one machine has one runner installed, then all jobs for your project
run on the same host:

1. Pipeline starts.
1. `job A` runs.
1. `before_script` is executed.
1. `script` is executed.
1. `after_script` is executed.
1. `cache` runs and the `vendor/` directory is zipped into `cache.zip`.
   This file is then saved in the directory based on the
   [runner's setting](#where-the-caches-are-stored) and the `cache: key`.
1. `job B` runs.
1. The cache is extracted (if found).
1. `before_script` is executed.
1. `script` is executed.
1. Pipeline finishes.

By using a single runner on a single machine, you don't have the issue where
`job B` might execute on a runner different from `job A`. This setup guarantees the
cache can be reused between stages. It only works if the execution goes from the `build` stage
to the `test` stage in the same runner/machine. Otherwise, the cache [might not be available](#cache-mismatch).

During the caching process, there's also a couple of things to consider:

- If some other job, with another cache configuration had saved its
  cache in the same zip file, it is overwritten. If the S3 based shared cache is
  used, the file is additionally uploaded to S3 to an object based on the cache
  key. So, two jobs with different paths, but the same cache key, overwrites
  their cache.
- When extracting the cache from `cache.zip`, everything in the zip file is
  extracted in the job's working directory (usually the repository which is
  pulled down), and the runner doesn't mind if the archive of `job A` overwrites
  things in the archive of `job B`.

It works this way because the cache created for one runner
often isn't valid when used by a different one. A different runner may run on a
different architecture (for example, when the cache includes binary files). Also,
because the different steps might be executed by runners running on different
machines, it is a safe default.

## Clearing the cache

Runners use [cache](../yaml/index.md#cache) to speed up the execution
of your jobs by reusing existing data. This can sometimes lead to
inconsistent behavior.

There are two ways to start with a fresh copy of the cache.

### Clear the cache by changing `cache:key`

Change the value for `cache: key` in your `.gitlab-ci.yml` file.
The next time the pipeline runs, the cache is stored in a different location.

### Clear the cache manually

You can clear the cache in the GitLab UI:

1. On the top bar, select **Main menu > Projects** and find your project.
1. On the left sidebar, select **CI/CD > Pipelines**.
1. In the upper-right corner, select **Clear runner caches**.

On the next commit, your CI/CD jobs use a new cache.

NOTE:
Each time you clear the cache manually, the [internal cache name](#where-the-caches-are-stored) is updated. The name uses the format `cache-<index>`, and the index increments by one. The old cache is not deleted. You can manually delete these files from the runner storage.

## Troubleshooting

### Cache mismatch

If you have a cache mismatch, follow these steps to troubleshoot.

| Reason for a cache mismatch | How to fix it |
| --------------------------- | ------------- |
| You use multiple standalone runners (not in autoscale mode) attached to one project without a shared cache. | Use only one runner for your project or use multiple runners with distributed cache enabled. |
| You use runners in autoscale mode without a distributed cache enabled. | Configure the autoscale runner to use a distributed cache. |
| The machine the runner is installed on is low on disk space or, if you've set up distributed cache, the S3 bucket where the cache is stored doesn't have enough space. | Make sure you clear some space to allow new caches to be stored. There's no automatic way to do this. |
| You use the same `key` for jobs where they cache different paths. | Use different cache keys so that the cache archive is stored to a different location and doesn't overwrite wrong caches. |

#### Cache mismatch example 1

If you have only one runner assigned to your project, the cache
is stored on the runner's machine by default.

If two jobs have the same cache key but a different path, the caches can be overwritten.
For example:

```yaml
stages:
  - build
  - test

job A:
  stage: build
  script: make build
  cache:
    key: same-key
    paths:
      - public/

job B:
  stage: test
  script: make test
  cache:
    key: same-key
    paths:
      - vendor/
```

1. `job A` runs.
1. `public/` is cached as cache.zip.
1. `job B` runs.
1. The previous cache, if any, is unzipped.
1. `vendor/` is cached as cache.zip and overwrites the previous one.
1. The next time `job A` runs it uses the cache of `job B` which is different
   and thus isn't effective.

To fix this issue, use different `keys` for each job.

#### Cache mismatch example 2

In this example, you have more than one runner assigned to your
project, and distributed cache is not enabled.

The second time the pipeline runs, you want `job A` and `job B` to re-use their cache (which in this case
is different):

```yaml
stages:
  - build
  - test

job A:
  stage: build
  script: build
  cache:
    key: keyA
    paths:
      - vendor/

job B:
  stage: test
  script: test
  cache:
    key: keyB
    paths:
      - vendor/
```

Even if the `key` is different, the cached files might get "cleaned" before each
stage if the jobs run on different runners in subsequent pipelines.