TExcelTAD
Home › Docker Compose › Compose in CI

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:

compose · try it yourself
# $ docker compose config -q
services:
  api:
    image: ghcr.io/acme/api:3.1
    enviroment:
      LOG_LEVEL: info
validating /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.

compose · try it yourself
# $ 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
  • tmpfs for 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 unused pgdata disappeared from the output.
  • cache_from / cache_to: type=gha stores BuildKit's layer cache in the GitHub Actions cache, so unchanged layers aren't rebuilt on every run. Other CI systems use type=registry,ref=….
  • -p ci-1234 gives the job its own project name: network ci-1234_default, containers ci-1234-db-1. Two pipelines on the same runner can't collide.
  • interval: 1s on 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:

bash
# 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 tests

Pattern 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:

python · try it yourself
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:

bash
$ 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-orphans

A complete GitHub Actions job

yaml
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-orphans

COMPOSE_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

python · try it yourself
# 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?

  1. Prints the config quietly in JSON
  2. Validates the configuration and prints nothing unless there is an error
  3. Queries the registry
  4. Runs the containers quietly

Why does each CI job use its own project name (-p ci-$RUN_ID)?

  1. Compose requires it in CI
  2. So parallel jobs on one runner get separate containers, networks and volumes
  3. To enable caching
  4. To push images

Which command reliably makes a CI step fail when the tests service fails?

  1. docker compose up
  2. docker compose up -d
  3. docker compose run --rm tests (or up --exit-code-from tests)
  4. docker compose logs tests