Docker in CI/CD
In a modern pipeline, the image is the artefact. CI builds it once from a commit, tests it, scans it, pushes it to a registry with traceable tags, and every environment (staging, production) deploys that exact image. "Works in CI" then really means "works in production", because it is the same bytes.
git push ─▶ build image ─▶ run tests in it ─▶ scan ─▶ push :sha-3f1c9a0 ─▶ deploy staging ─▶ promote :2.4.1 ─▶ productionA GitHub Actions workflow
# .github/workflows/docker.yml
name: image
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
if: github.event_name != 'pull_request'
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v6
id: meta
with:
images: ghcr.io/acme/shop-api
tags: |
type=sha
type=ref,event=branch
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Test
run: docker compose -f compose.yaml -f compose.ci.yaml run --rm tests
- uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=maxKey ideas in that file:
- Pull requests build but don't push. Only
mainand version tags publish images. - Tags come from Git:
sha-<commit>, the branch name, and semantic versions fromv2.4.1tags. - Cache export/import (
cache-from/cache-to) brings back the layer cache that a fresh CI runner wouldn't have. - Multi-platform: Buildx builds
amd64andarm64variants under one tag (a manifest list).
Tags from Git refs
This model reproduces what a metadata step computes for different kinds of pushes:
import re
def ci_tags(event, ref, sha, image="ghcr.io/acme/shop-api"):
tags = [f"sha-{sha[:7]}"]
if event == "pull_request":
return [], f"build only (no push), would tag pr-{ref.split('/')[2]}"
if ref.startswith("refs/heads/"):
branch = ref.removeprefix("refs/heads/")
tags.append(re.sub(r"[^a-zA-Z0-9_.-]", "-", branch))
m = re.fullmatch(r"refs/tags/v(\d+)\.(\d+)\.(\d+)", ref)
if m:
major, minor, patch = m.groups()
tags += [f"{major}.{minor}.{patch}", f"{major}.{minor}", "latest"]
return [f"{image}:{t}" for t in tags], "push"
for event, ref, sha in [
("push", "refs/heads/main", "3f1c9a0d7b2e41"),
("push", "refs/heads/feature/cart-v2", "a91b22c0ffee00"),
("push", "refs/tags/v2.4.1", "77ab01c4e5f6aa"),
("pull_request", "refs/pull/128/merge", "5d5d5d5d5d5d5d"),
]:
tags, action = ci_tags(event, ref, sha)
print(f"{ref:<28} {action}")
for t in tags:
print(f" {t}")refs/heads/main push
ghcr.io/acme/shop-api:sha-3f1c9a0
ghcr.io/acme/shop-api:main
refs/heads/feature/cart-v2 push
ghcr.io/acme/shop-api:sha-a91b22c
ghcr.io/acme/shop-api:feature-cart-v2
refs/tags/v2.4.1 push
ghcr.io/acme/shop-api:sha-77ab01c
ghcr.io/acme/shop-api:2.4.1
ghcr.io/acme/shop-api:2.4
ghcr.io/acme/shop-api:latest
refs/pull/128/merge build only (no push), would tag pr-128
Note how feature/cart-v2 became feature-cart-v2: a / is not allowed in a tag.
Caching in CI
A CI runner usually starts with an empty Docker cache, so without help every build re-installs every dependency. The fix is to store the cache somewhere persistent: the GitHub Actions cache (type=gha), a registry (type=registry,ref=ghcr.io/acme/shop-api:buildcache), or a local directory. The model compares build times:
steps = [("FROM + apt packages", 35), ("install dependencies", 95), ("COPY source", 1), ("compile / collect static", 20)]
def build_time(cache_hits):
return sum(0.5 if hit else secs for (name, secs), hit in zip(steps, cache_hits))
scenarios = {
"cold runner, no cache import": [False, False, False, False],
"cache imported, only source changed": [True, True, False, False],
"cache imported, dependencies changed": [True, False, False, False],
}
for label, hits in scenarios.items():
print(f"{label:<40} {build_time(hits):6.1f} s")cold runner, no cache import 151.0 s
cache imported, only source changed 22.0 s
cache imported, dependencies changed 116.5 s
Testing the image
Run your tests inside the built image (or a test target of the same Dockerfile), so you test what you ship:
docker build --target test -t shop:test .
docker run --rm shop:test pytest -q
docker compose -f compose.yaml -f compose.ci.yaml up --abort-on-container-exit --exit-code-from tests--exit-code-from tests makes the Compose command fail when the test container fails, which fails the CI job.
Deploying
- Promote, don't rebuild: deploy to production the same digest that passed staging (
docker buildx imagetools create -t ...:2.4.1 ...@sha256:...retags without rebuilding). - Deploy by digest or immutable tag, never by
latest. - On a single server, deployment can be as simple as
docker compose pull && docker compose up -d. Larger systems hand the new tag to Kubernetes, ECS, Cloud Run or similar.
Docker-in-Docker vs socket mounting
Self-hosted CI runners that build images need access to a Docker engine. Mounting the host's /var/run/docker.sock into the CI job is fast but gives every job root on the host. Safer options are a dedicated rootless BuildKit or Docker-in-Docker service per job, or a remote builder.
Test yourself
Why should production deploy the same image digest that passed staging instead of rebuilding from the same commit?
- Rebuilding is not allowed
- A rebuild can pick up different base images or dependencies; the digest guarantees identical bytes
- Digests are shorter
- Registries charge for builds
What do cache-from / cache-to solve in CI?
- They speed up pushes
- Fresh CI runners have no local layer cache, so the cache is exported and imported between runs
- They encrypt images
- They run tests
A branch is called feature/login. Why is the CI tag feature-login?
- Docker tags can't contain
/ - Dashes are faster
- It's a GitHub requirement
- To hide the branch name