Compose in CI
Integration tests need the real neighbours: a real PostgreSQL, a real Redis, maybe a fake S3. Installing all of that on a CI runner is slow and never quite matches production. Compose is a natural fit: the same file that developers use locally starts the dependencies in CI, the tests run in a container next to them, and everything is thrown away afterwards.
This lesson builds a CI setup step by step: linting the compose files, a CI override, running tests with the right exit code, isolating parallel jobs, caching builds, and cleaning up. The Docker CI/CD lesson covers building and pushing images; here the focus is on Compose.
Step 1: lint the configuration
The cheapest check in the pipeline: does every combination of files you deploy actually render? config -q prints nothing on success and fails on errors, such as a misspelled key:
# $ docker compose config -q
services:
api:
image: ghcr.io/acme/api:3.1
enviroment:
LOG_LEVEL: infovalidating /home/ada/demo/compose.yaml: services.api.enviroment false schema
Without -q-style validation, a typo like enviroment would be a silent bug: the variable would simply never reach the container. Run the check for every file combination (-f compose.yaml -f compose.prod.yaml config -q, …), with the production variables set to dummy values, so required ${VAR:?} checks pass.
Step 2: a CI override
CI wants a few things to be different from development: no bind mounts, no published ports, no persistent volumes (a fresh database every run), and a test runner service.
# $ docker compose -f compose.yaml -f compose.ci.yaml -p ci-1234 config --no-path-resolution
services:
api:
build: .
image: ghcr.io/acme/api:${GIT_SHA:-local}
db:
image: postgres:17
environment:
POSTGRES_PASSWORD: ci
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 1s
retries: 30
volumes: [pgdata:/var/lib/postgresql/data]
volumes:
pgdata:
# --- compose.ci.yaml
services:
api:
build:
cache_from: [type=gha]
cache_to: ["type=gha,mode=max"]
db:
volumes: !reset []
tmpfs: [/var/lib/postgresql/data]
tests:
image: ghcr.io/acme/api:${GIT_SHA:-local}
command: ["pytest", "-q", "--junitxml=/reports/junit.xml"]
environment:
DATABASE_URL: postgres://postgres:ci@db:5432/postgres
depends_on:
db: {condition: service_healthy}name: ci-1234
services:
api:
image: ghcr.io/acme/api:local
networks:
default: null
build:
context: .
dockerfile: Dockerfile
cache_from:
- type=gha
cache_to:
- type=gha,mode=max
db:
environment:
POSTGRES_PASSWORD: ci
image: postgres:17
networks:
default: null
tmpfs:
- /var/lib/postgresql/data
healthcheck:
test:
- CMD-SHELL
- pg_isready -U postgres
interval: 1s
retries: 30
tests:
command:
- pytest
- -q
- --junitxml=/reports/junit.xml
environment:
DATABASE_URL: postgres://postgres:ci@db:5432/postgres
image: ghcr.io/acme/api:local
networks:
default: null
depends_on:
db:
condition: service_healthy
required: true
networks:
default:
name: ci-1234_default
tmpfsfor the database instead of a volume: Postgres writes to RAM, which makes migration-heavy test suites noticeably faster, and nothing survives the job. The volume was removed with!reset [], and the unusedpgdatadisappeared from the output.cache_from/cache_to: type=ghastores BuildKit's layer cache in the GitHub Actions cache, so unchanged layers aren't rebuilt on every run. Other CI systems usetype=registry,ref=….-p ci-1234gives the job its own project name: networkci-1234_default, containersci-1234-db-1. Two pipelines on the same runner can't collide.interval: 1son the healthcheck: in CI every second of waiting counts.
Step 3: run the tests, get the right exit code
The CI step must fail when the tests fail. There are two common patterns:
# A: run the test container as a one-off; its exit code is run's exit code
$ docker compose -p "ci-$RUN_ID" run --rm tests
# B: up everything, stop when tests finish, use the tests' exit code
$ docker compose -p "ci-$RUN_ID" up --build --abort-on-container-exit --exit-code-from testsPattern A is usually clearer: run starts db (respecting the healthcheck condition), runs the tests, and returns pytest's exit code. Pattern B shows all services' logs interleaved, which helps when the failure is in a dependency. A model of how pattern B decides its exit code:
def up_exit_code(events, exit_code_from=None, abort_on_exit=False):
"""events: list of (service, exit_code) in the order containers exit."""
codes = {}
for service, code in events:
print(f" {service} exited with {code}")
codes[service] = code
if abort_on_exit:
print(" --abort-on-container-exit: stopping all other containers (SIGTERM)")
break
if exit_code_from:
return codes.get(exit_code_from, 143) # still running when stopped: killed by SIGTERM
return 0 # plain `up` doesn't report the tests' result
print("tests fail:")
print(" => step exit code", up_exit_code([("tests", 1)], "tests", True))
print("db crashes first:")
print(" => step exit code", up_exit_code([("db", 137), ("tests", 0)], "tests", True))
print("plain up, tests fail:")
print(" => step exit code", up_exit_code([("tests", 1)]))tests fail:
tests exited with 1
--abort-on-container-exit: stopping all other containers (SIGTERM)
=> step exit code 1
db crashes first:
db exited with 137
--abort-on-container-exit: stopping all other containers (SIGTERM)
=> step exit code 143
plain up, tests fail:
tests exited with 1
=> step exit code 0
The second case is the trap: with --abort-on-container-exit, the first container to exit stops everything. If db dies first, the tests are stopped before they finish, and the job fails with the tests' SIGTERM code (143) instead of a test report. The third case is worse: plain up is not designed to report a test result, so a failing suite can leave the step green. Always use --exit-code-from (or run).
Step 4: always clean up
CI runners are often reused. Clean up even when a previous step failed:
$ docker compose -p "ci-$RUN_ID" logs --no-color > compose-logs.txt # keep logs as an artifact
$ docker compose -p "ci-$RUN_ID" down -v --remove-orphansA complete GitHub Actions job
name: integration
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
env:
COMPOSE_FILE: compose.yaml:compose.ci.yaml
COMPOSE_PROJECT_NAME: ci-${{ github.run_id }}
GIT_SHA: ${{ github.sha }}
steps:
- uses: actions/checkout@v7
- uses: docker/setup-buildx-action@v4
- name: Lint compose files
run: |
docker compose config -q
API_TAG=ci docker compose -f compose.yaml -f compose.prod.yaml config -q
- name: Build
run: docker compose build api
- name: Test
run: docker compose run --rm tests
- name: Collect logs
if: failure()
run: docker compose logs --no-color > compose-logs.txt
- uses: actions/upload-artifact@v4
if: failure()
with: {name: compose-logs, path: compose-logs.txt}
- name: Clean up
if: always()
run: docker compose down -v --remove-orphansCOMPOSE_FILE and COMPOSE_PROJECT_NAME as job-level variables mean every step uses the same files and project without repeating -f/-p (see Project Names).
Making it fast
# rough CI timings in seconds, before and after common improvements
stages = ["pull images", "build", "start + wait healthy", "migrate", "tests"]
before = [25, 140, 30, 20, 180]
after = [ 8, 15, 6, 4, 120] # pre-pulled/cached images, gha cache, 1s healthchecks, tmpfs db, pytest -n 4
for s, b, a in zip(stages, before, after):
print(f"{s:<22} {b:>4}s -> {a:>4}s")
print(f"{'total':<22} {sum(before):>4}s -> {sum(after):>4}s")pull images 25s -> 8s
build 140s -> 15s
start + wait healthy 30s -> 6s
migrate 20s -> 4s
tests 180s -> 120s
total 395s -> 153s
The biggest wins are usually the build cache and a database that doesn't hit disk. Pin image versions (postgres:17.6, not postgres:latest) so CI is reproducible, and use the same major versions as production.
Learn more: Docker CI/CD · Override Files & Merging · Compose in Production · GitOps
Test yourself
What does docker compose config -q do?
- Prints the config quietly in JSON
- Validates the configuration and prints nothing unless there is an error
- Queries the registry
- Runs the containers quietly
Why does each CI job use its own project name (-p ci-$RUN_ID)?
- Compose requires it in CI
- So parallel jobs on one runner get separate containers, networks and volumes
- To enable caching
- To push images
Which command reliably makes a CI step fail when the tests service fails?
- docker compose up
- docker compose up -d
- docker compose run --rm tests (or up --exit-code-from tests)
- docker compose logs tests