Docker Compose — Compose in CI/CD

1 minute read

Use Docker Compose in CI/CD pipelines to build, test, and deploy your applications.

GitHub Actions

name: CI
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build images
        run: docker compose build

      - name: Run tests
        run: docker compose run --rm api npm test

      - name: Integration tests
        run: |
          docker compose up -d
          docker compose exec api npm run test:integration
          docker compose down -v

GitLab CI

test:
  image: docker:latest
  services:
    - docker:dind
  script:
    - docker compose build
    - docker compose run --rm api npm test
    - docker compose down -v

Build + Push Pattern

name: Deploy
on:
  push:
    tags: ["v*"]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Login to registry
        run: echo "$TOKEN" | docker login ghcr.io -u $USER --password-stdin

      - name: Build and push
        env:
          VERSION: ${{ github.ref_name }}
        run: |
          docker compose build
          docker compose push

Test Patterns

Run and Exit

docker compose run --rm --exit-code-from test test

The --exit-code-from returns the exit code of the test service — CI fails if tests fail.

Abort on Failure

docker compose up --abort-on-container-exit --exit-code-from test

Stops all services when test exits and returns its exit code.

CI Best Practices

Practice Reason
Use --rm Clean up test containers
Use --exit-code-from Propagate test exit code
Use down -v Clean up volumes after tests
Pin image versions Reproducible builds
Cache layers Faster CI builds
Use --pull Get latest base images

Docker Compose in Production

While Compose is great for development and small deployments, consider:

Scale Recommendation
Single server Docker Compose works great
Small team Compose + CI/CD pipeline
Multiple servers Docker Swarm or Kubernetes
Enterprise Kubernetes + Helm

Summary

CI/CD Task Command
Build docker compose build
Test docker compose run --rm test
Integration test docker compose up + exec
Push docker compose push
Cleanup docker compose down -v

Quick Reference

Item Detail
build docker compose build in CI
test docker compose run –rm test
–exit-code-from Return service exit code
–abort-on-container-exit Stop all on test exit
push docker compose push to registry
cleanup docker compose down -v