Docker and Container WorkflowsLesson 3.3
How to run service containers for integration tests in GitHub Actions
services block, postgres service container, redis service, health checks, port mapping, environment variables for services, container networking
Service Containers
Integration tests often need real databases or caches — not mocks. GitHub Actions service containers spin up Docker containers alongside your job and expose them on localhost. They start before your steps run and stop after the job finishes.
PostgreSQL Service Example
jobs:
integration-test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: testpassword
POSTGRES_DB: testdb
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run test:integration
env:
DATABASE_URL: postgresql://postgres:testpassword@localhost:5432/testdbThe options field passes health check flags to the container. GitHub waits until the health check passes before starting your steps — this prevents tests from failing because they connect before PostgreSQL is ready. The service is reachable at localhost on the mapped port.
