Overview and What You Will Learn
You can run Docker Compose inside a GitHub Actions job to start real PostgreSQL, Redis, and RabbitMQ instances, run integration tests against them, and discard everything afterwards. GitHub-hosted Ubuntu runners include Docker and Compose, so no extra installation is needed.
In this lab you will:
- Write a CI-specific Compose override that exposes dependency ports.
- Start the stack with
docker compose up -d --waitinstead of sleep loops. - Seed test data with a profile-based one-shot service.
- Run integration tests from the runner against the services.
- Capture logs when a run fails, and tear down reliably.
Why This Matters in Production
Mocked database calls miss the bugs that hurt most: a JOIN that returns duplicate rows, a Redis key that expires mid-request, a message that is never acknowledged. Running tests against the same engines you use in production catches these before merge, when the failing commit is still obvious.
CI dependencies should be ephemeral and isolated per run. A fresh PostgreSQL container for every pull request means no leftover rows, no test pollution, and no flaky failures from a shared staging database that other engineers are using at the same time.
Core Principles
Each CI run starts a clean stack, waits for health, tests, collects evidence on failure, and removes everything.
Principles worth remembering:
- Wait on health, not time.
--waitblocks until every service with a health check is healthy. - Layer CI settings on the base file. A second
-ffile changes ports and credentials without duplicating services. - Use fake credentials. CI passwords should be valid only inside the ephemeral stack.
- Always collect logs on failure. A CI failure you cannot inspect is a failure you will re-run and hope about.
- Always tear down. On GitHub-hosted runners the VM is discarded anyway, but self-hosted runners keep containers and volumes unless you remove them.
Detailed Step-by-Step Practical Lab
How to Write a CI Compose Override
services: postgres: ports: - "55432:5432" # distinct host port avoids clashes on shared runners environment: POSTGRES_PASSWORD: ci-only-password healthcheck: test: ["CMD-SHELL", "pg_isready -U api_user -d payments_test"] interval: 3s timeout: 2s retries: 10 redis: ports: - "56379:6379" test-seeder: build: ./scripts/seed profiles: ["ci"] # never starts in normal local runs depends_on: postgres: condition: service_healthy environment: DATABASE_URL: postgres://api_user:ci-only-password@postgres:5432/payments_testIf you prefer not to fix host ports at all, omit the left side ("5432") and discover the assigned port with docker compose port postgres 5432.
How to Write the GitHub Actions Workflow
# .github/workflows/integration-tests.ymlname: Integration Tests on: pull_request: branches: [main] jobs: integration-tests: runs-on: ubuntu-latest timeout-minutes: 15 env: COMPOSE_FILE: compose.yaml:compose.ci.yaml steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: "20" cache: npm - name: Install dependencies run: npm ci - name: Start dependency stack and wait for health run: docker compose up -d --wait --wait-timeout 90 postgres redis - name: Seed test data run: docker compose --profile ci run --rm test-seeder - name: Run integration tests env: DATABASE_URL: postgres://api_user:ci-only-password@localhost:55432/payments_test REDIS_URL: redis://localhost:56379 run: npm run test:integration - name: Collect logs on failure if: failure() run: docker compose logs --no-color --timestamps > compose-logs.txt - name: Upload failure logs if: failure() uses: actions/upload-artifact@v4 with: name: compose-logs path: compose-logs.txt - name: Tear down stack if: always() run: docker compose down --volumes --remove-orphansSetting COMPOSE_FILE with colon-separated paths applies both files to every docker compose command in the job, so you do not repeat -f flags.
Why the Seeder Runs with run Instead of up
A one-shot service exits when it finishes. Starting it through up --wait can be treated as a failure because the container is no longer running. Using docker compose --profile ci run --rm test-seeder after the stack is healthy keeps the exit code meaningful: a non-zero exit fails the step.
How to Debug a Failed CI Run
# All services, no colour codes, with timestamps to line up with test outputdocker compose logs --no-color --timestamps > compose-logs.txt # One suspicious servicedocker compose logs --no-color postgres > postgres-logs.txt # Show the merged configuration that CI actually useddocker compose configHow to Cache Images You Build in CI
If your stack builds a custom image, let Buildx cache layers in the GitHub Actions cache and load the result for Compose to use.
- uses: docker/setup-buildx-action@v3- uses: docker/build-push-action@v6 with: context: . load: true tags: payment-api:ci cache-from: type=gha cache-to: type=gha,mode=maxReference image: payment-api:ci in compose.ci.yaml with pull_policy: never so Compose uses the loaded image. Pulled images such as postgres:16-alpine rarely need caching on hosted runners.
Production Best Practices & Common Pitfalls
- Use
--waitinstead ofsleep: it follows each service's health check, so it is fast when ready and strict when slow. - Keep CI-only services behind a profile: seed and mock services should not start in ordinary local runs.
- Use
if: always()on teardown: otherwise a failed test step skips cleanup on self-hosted runners. - Pin images:
postgres:16-alpine, notpostgres:latest, so a new major version cannot break CI overnight. - Set
timeout-minutes: a hung health check should not burn runner minutes for hours. - Do not mount persistent volumes in CI: a fresh, empty database every run is the goal.
TipRun the same commands locally with
COMPOSE_FILE=compose.yaml:compose.ci.yaml docker compose up -d --waitto reproduce a CI failure on your machine.
RememberMultiple Compose files merge in order, and later files override earlier ones.
compose.yamlfirst, thencompose.ci.yaml, gives the base services with CI changes on top.
Common MistakeOmitting
if: always()on the teardown step. After a failing test the workflow skips later steps by default, leaving containers and volumes behind on self-hosted runners.
SecurityNever put production credentials in CI Compose files or logs. Use throwaway values such as
ci-only-passwordthat have no meaning outside the ephemeral stack, and store real secrets in GitHub encrypted secrets.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker compose up -d --wait |
Start services and wait for health |
docker compose --profile ci run --rm test-seeder |
Run the one-shot seeder |
docker compose logs --no-color --timestamps |
Dump logs for a CI artifact |
docker compose port postgres 5432 |
Show the assigned host port |
docker compose down --volumes --remove-orphans |
Full cleanup |
docker compose config |
Show the merged configuration |
| Problem | Likely cause | Fix |
|---|---|---|
| Tests fail intermittently on startup | Not waiting for health | Use up --wait with health checks |
--wait fails with exited container |
One-shot service in up |
Run it with docker compose run --rm |
| Port already in use on runner | Fixed port clashes with another job | Use distinct ports or let Docker assign them |
| Cannot see why a run failed | Logs not collected | Upload docker compose logs as an artifact |
| Leftover containers on runner | Teardown skipped | Add if: always() to teardown |