Index · Caching · Ci · Help (2024)

GitLab CI/CD provides a caching mechanism that can be used to save timewhen your jobs are running.

Caching is about speeding the time a job is executed by reusing the samecontent of a previous job. It can be particularly useful when you aredeveloping software that depends on other libraries which are fetched via theinternet during build time.

If caching is enabled, it's shared between pipelines and jobs at the projectlevel by default, starting from GitLab 9.0. Caches are not shared acrossprojects.

Make sure you read the cache reference to learnhow it is defined in .gitlab-ci.yml.

Cache vs artifacts

Be careful if you use cache and artifacts to store the same path in your jobsas caches are restored before artifacts and the content could be overwritten.

Don't use caching for passing artifacts between stages, as it is designed to storeruntime dependencies needed to compile the project:

  • cache: For storing project dependencies

    Caches are used to speed up runs of a given job in subsequent pipelines, bystoring downloaded dependencies so that they don't have to be fetched from theinternet again (like npm packages, Go vendor packages, etc.) While the cache couldbe configured to pass intermediate build results between stages, this should bedone with artifacts instead.

  • artifacts: Use for stage results that will be passed between stages.

    Artifacts are files generated by a job which are stored and uploaded, and can thenbe fetched and used by jobs in later stages of the same pipeline. In other words,you can't create an artifact in job-A in stage-1, and then use this artifact in job-B in stage-1.This data will not be available in different pipelines, but is available to be downloadedfrom the UI.

The name artifacts sounds like it's only useful outside of the job, like for downloadinga final image, but artifacts are also available in later stages within a pipeline.So if you build your application by downloading all the required modules, you mightwant to declare them as artifacts so that subsequent stages can use them. There aresome optimizations like declaring an expiry timeso you don't keep artifacts around too long, or using dependenciesto control which jobs fetch the artifacts.

Caches:

  • Are disabled if not defined globally or per job (using cache:).
  • Are available for all jobs in your .gitlab-ci.yml if enabled globally.
  • Can be used in subsequent pipelines by the same job in which the cache was created (if not defined globally).
  • Are stored where GitLab Runner is installed and uploaded to S3 if distributed cache is enabled.
  • If defined per job, are used:
    • By the same job in a subsequent pipeline.
    • By subsequent jobs in the same pipeline, if they have identical dependencies.

Artifacts:

  • Are disabled if not defined per job (using artifacts:).
  • Can only be enabled per job, not globally.
  • Are created during a pipeline and can be used by the subsequent jobs of that currently active pipeline.
  • Are always uploaded to GitLab (known as coordinator).
  • Can have an expiration value for controlling disk usage (30 days by default).

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

Good caching practices

We have the cache from the perspective of the developers (who consume a cachewithin the job) and the cache from the perspective of the runner. Depending onwhich type of runner you are using, cache can act differently.

From the perspective of the developer, to ensure maximum availability of thecache, when declaring cache in your jobs, use one or a mix of the following:

  • Tag your runners and use the tag on jobsthat share their cache.
  • Use sticky runnersthat will be only available to a particular project.
  • Use a key that fits your workflow (for example,different caches on each branch). For that, you can take advantage of theCI/CD predefined variables.

TIP: Tip:Using the same runner for your pipeline, is the most simple and efficient way tocache files in one stage or pipeline, and pass this cache to subsequent stagesor pipelines in a guaranteed manner.

From the perspective of the runner, in order for cache to work effectively, oneof the following must be true:

  • Use a single runner for all your jobs.
  • Use multiple runners (in autoscale mode or not) that usedistributed caching,where the cache is stored in S3 buckets (like shared runners on GitLab.com).
  • Use multiple runners (not in autoscale mode) of the same architecture thatshare a common network-mounted directory (using NFS or something similar)where the cache will be stored.

TIP: Tip:Read about the availability of the cacheto learn more about the internals and get a better idea how cache works.

Sharing caches across the same branch

Define a cache with the key: ${CI_COMMIT_REF_SLUG} so that jobs of eachbranch always use the same cache:

cache: key: ${CI_COMMIT_REF_SLUG}

While this feels like it might be safe from accidentally overwriting the cache,it means merge requests get slow first pipelines, which might be a baddeveloper experience. The next time a new commit is pushed to the branch, thecache will be re-used.

To enable per-job and per-branch caching:

cache: key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"

To enable per-branch and per-stage caching:

cache: key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"

Sharing caches across different branches

If the files you are caching need to be shared across all branches and all jobs,you can use the same key for all of them:

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

To share the same cache between branches, but separate them by job:

cache: key: ${CI_JOB_NAME}

Disabling cache on specific jobs

If you have defined the cache globally, it means that each job will use thesame definition. You can override this behavior per-job, and if you want todisable it completely, use an empty hash:

job: cache: {}

Inherit global config, but override specific settings per job

You can override cache settings without overwriting the global cache by usinganchors. For example, if you want to override thepolicy for one job:

cache: &global_cache key: ${CI_COMMIT_REF_SLUG} paths: - node_modules/ - public/ - vendor/ policy: pull-pushjob: cache: # inherit all global cache settings <<: *global_cache # override the policy policy: pull

For more fine tuning, read also about thecache: policy.

Common use cases

The most common use case of cache is to preserve contents between subsequentruns of jobs for things like dependencies and commonly used libraries(Node.js packages, PHP packages, rubygems, Python libraries, etc.),so they don't have to be re-fetched from the public internet.

For more examples, check out our GitLab CI/CD templates.

Caching Node.js dependencies

Assuming your project is using npm to install the Node.jsdependencies, the following example defines cache globally so that all jobs inherit it.By default, npm stores cache data in the home folder ~/.npm but sinceyou can't cache things outside of the project directory,we tell npm to use ./.npm instead, and it is cached per-branch:

## https://gitlab.com/gitlab-org/gitlab/tree/master/lib/gitlab/ci/templates/Nodejs.gitlab-ci.yml#image: node:latest# Cache modules in between jobscache: key: ${CI_COMMIT_REF_SLUG} paths: - .npm/before_script: - npm ci --cache .npm --prefer-offlinetest_async: script: - node ./specs/start.js ./specs/async.spec.js

Caching PHP dependencies

Assuming your project is using Composer to installthe PHP dependencies, the following example defines cache globally so thatall jobs inherit it. PHP libraries modules are installed in vendor/ andare cached per-branch:

## https://gitlab.com/gitlab-org/gitlab/tree/master/lib/gitlab/ci/templates/PHP.gitlab-ci.yml#image: php:7.2# Cache libraries in between jobscache: 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 installtest: script: - vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never

Caching Python dependencies

Assuming your project is using pip to installthe Python dependencies, the following example defines cache globally so thatall jobs inherit it. Python libraries are installed in a virtual environment under venv/,pip's cache is defined under .cache/pip/ and both are cached per-branch:

## 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## If you want to also cache the installed packages, you have to install# them in a virtualenv and cache it as well.cache: paths: - .cache/pip - venv/before_script: - python -V # Print out python version for debugging - pip install virtualenv - virtualenv venv - source venv/bin/activatetest: script: - python setup.py test - pip install flake8 - flake8 .

Caching Ruby dependencies

Assuming your project is using Bundler to install thegem dependencies, the following example defines cache globally so that alljobs inherit it. Gems are installed in vendor/ruby/ and are cached per-branch:

## https://gitlab.com/gitlab-org/gitlab/tree/master/lib/gitlab/ci/templates/Ruby.gitlab-ci.yml#image: ruby:2.6# Cache gems in between buildscache: key: ${CI_COMMIT_REF_SLUG} paths: - vendor/rubybefore_script: - ruby -v # Print out ruby version for debugging - bundle install -j $(nproc) --path vendor/ruby # Install dependencies into ./vendor/rubyrspec: script: - rspec spec

Caching Go dependencies

Assuming your project is using Go Modules to installGo dependencies, the following example defines cache in a go-cache template, thatany job can extend. Go modules are installed in ${GOPATH}/pkg/mod/ andare cached for all of the go projects:

.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 isn't guaranteed to always work, so you need tobe prepared to regenerate any cached files in each job that needs them.

Assuming you have properly defined cache in .gitlab-ci.ymlaccording to your workflow, the availability of the cache ultimately depends onhow the runner has been configured (the executor type and whether differentrunners are used for passing the cache between jobs).

Where the caches are stored

Since the runner is the one responsible for storing the cache, it's essentialto know where it's stored. All the cache paths defined under a job in.gitlab-ci.yml are archived in a single cache.zip file and stored in therunner's configured cache location. By default, they are stored locally in themachine where the runner is installed and depends on the type of the executor.

GitLab Runner executorDefault path of the cache
ShellLocally, stored under the gitlab-runner user's home directory: /home/gitlab-runner/cache/<user>/<project>/<cache-key>/cache.zip.
DockerLocally, stored under Docker volumes: /var/lib/docker/volumes/<volume-id>/_data/<user>/<project>/<cache-key>/cache.zip.
Docker machine (autoscale runners)Behaves the same as the Docker executor.

How archiving and extracting works

In the most simple scenario, consider that you use only one machine where therunner is installed, and all jobs of your project run on the same host.

Let's see the following example of two jobs that belong to two consecutivestages:

stages: - build - testbefore_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/

Here's what happens behind the scenes:

  1. Pipeline starts.
  2. job A runs.
  3. before_script is executed.
  4. script is executed.
  5. after_script is executed.
  6. cache runs and the vendor/ directory is zipped into cache.zip.This file is then saved in the directory based on therunner's setting and the cache: key.
  7. job B runs.
  8. The cache is extracted (if found).
  9. before_script is executed.
  10. script is executed.
  11. Pipeline finishes.

By using a single runner on a single machine, you'll not have the issue wherejob B might execute on a runner different from job A, thus guaranteeing thecache between stages. That will only work if the build goes from stage buildto test in the same runner/machine, otherwise, you might not have the cacheavailable.

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

  • If some other job, with another cache configuration had saved itscache in the same zip file, it is overwritten. If the S3 based shared cache isused, the file is additionally uploaded to S3 to an object based on the cachekey. So, two jobs with different paths, but the same cache key, will overwritetheir cache.
  • When extracting the cache from cache.zip, everything in the zip file isextracted in the job's working directory (usually the repository which ispulled down), and the runner doesn't mind if the archive of job A overwritesthings in the archive of job B.

The reason why it works this way is because the cache created for one runneroften will not be valid when used by a different one which can run on adifferent architecture (e.g., when the cache includes binary files). Andsince the different steps might be executed by runners running on differentmachines, it is a safe default.

Cache mismatch

In the following table, you can see some reasons where you might hit a cachemismatch and a few ideas how to fix it.

Reason of a cache mismatchHow to fix it
You use multiple standalone runners (not in autoscale mode) attached to one project without a shared cacheUse only one runner for your project or use multiple runners with distributed cache enabled
You use runners in autoscale mode without a distributed cache enabledConfigure 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 spaceMake sure you clear some space to allow new caches to be stored. Currently, there's no automatic way to do this.
You use the same key for jobs where they cache different paths.Use different cache keys to that the cache archive is stored to a different location and doesn't overwrite wrong caches.

Let's explore some examples.

Examples

Let's assume you have only one runner assigned to your project, so the cachewill be stored in the runner's machine by default. If two jobs, A and B,have the same cache key, but they cache different paths, cache B would overwritecache A, even if their paths don't match:

We want job A and job B to re-use theircache when the pipeline is run for a second time.

stages: - build - testjob 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.
  2. public/ is cached as cache.zip.
  3. job B runs.
  4. The previous cache, if any, is unzipped.
  5. vendor/ is cached as cache.zip and overwrites the previous one.
  6. The next time job A runs it will use the cache of job B which is differentand thus will be ineffective.

To fix that, use different keys for each job.

In another case, let's assume you have more than one runner assigned to yourproject, but the distributed cache is not enabled. The second time thepipeline is run, we want job A and job B to re-use their cache (which in this casewill be different):

stages: - build - testjob A: stage: build script: build cache: key: keyA paths: - vendor/job B: stage: test script: test cache: key: keyB paths: - vendor/

In that case, even if the key is different (no fear of overwriting), youmight experience that the cached files "get cleaned" before each stage if thejobs run on different runners in the subsequent pipelines.

Clearing the cache

Runners use cache to speed up the executionof your jobs by reusing existing data. This however, can sometimes lead to aninconsistent behavior.

To start with a fresh copy of the cache, there are two ways to do that.

Clearing the cache by changing cache:key

All you have to do is set a new cache: key in your .gitlab-ci.yml. In thenext run of the pipeline, the cache will be stored in a different location.

Clearing the cache manually

Introduced in GitLab 10.4.

If you want to avoid editing .gitlab-ci.yml, you can easily clear the cachevia GitLab's UI:

  1. Navigate to your project's CI/CD > Pipelines page.

  2. Click on the Clear runner caches button to clean up the cache.

  3. On the next push, your CI/CD job will use a new cache.

Behind the scenes, this works by increasing a counter in the database, and thevalue of that counter is used to create the key for the cache by appending aninteger to it: -1, -2, etc. After a push, a new key is generated and theold cache is not valid anymore.

Index · Caching · Ci · Help (2024)
Top Articles
Proverbs 11:12-13 Whoever derides their neighbor has no sense, but the one who has understanding holds their tongue. A gossip betrays a confidence, but a trustworthy person keeps a secret. | New International Version (NIV) | Download The Bible App Now
6 reasons why you may be denied a credit card
Mybranch Becu
The Blackening Showtimes Near Century Aurora And Xd
neither of the twins was arrested,传说中的800句记7000词
Www.paystubportal.com/7-11 Login
Ups Stores Near
Amc Near My Location
Algebra Calculator Mathway
Get train & bus departures - Android
The Ivy Los Angeles Dress Code
THE 10 BEST Women's Retreats in Germany for September 2024
The Realcaca Girl Leaked
Craigslist In South Carolina - Craigslist Near You
Is Csl Plasma Open On 4Th Of July
Locate Td Bank Near Me
How Quickly Do I Lose My Bike Fitness?
Bc Hyundai Tupelo Ms
Sarpian Cat
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
Craigslist Pets Athens Ohio
Vcuapi
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Conan Exiles Colored Crystal
Gayla Glenn Harris County Texas Update
Kountry Pumpkin 29
Mychart Anmed Health Login
Poe Str Stacking
Pecos Valley Sunland Park Menu
Dallas Mavericks 110-120 Golden State Warriors: Thompson leads Warriors to Finals, summary score, stats, highlights | Game 5 Western Conference Finals
Cable Cove Whale Watching
Vivification Harry Potter
Wbap Iheart
Funky Town Gore Cartel Video
Free Tiktok Likes Compara Smm
Radical Red Doc
Midsouthshooters Supply
Heelyqutii
Encompass.myisolved
Electronic Music Duo Daft Punk Announces Split After Nearly 3 Decades
Invalleerkracht [Gratis] voorbeelden van sollicitatiebrieven & expert tips
Walmart Pharmacy Hours: What Time Does The Pharmacy Open and Close?
Janaki Kalaganaledu Serial Today Episode Written Update
Brandon Spikes Career Earnings
Gotrax Scooter Error Code E2
Sallisaw Bin Store
Wordle Feb 27 Mashable
Hk Jockey Club Result
Unit 11 Homework 3 Area Of Composite Figures
Haunted Mansion Showtimes Near Millstone 14
Public Broadcasting Service Clg Wiki
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 6268

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.