DevOps / GitHub Actions Interview Questions
How do you set up a Docker container service for integration tests using services: in GitHub Actions?
The services: block on a job starts Docker containers as side-cars alongside the job's steps. This lets you spin up a real PostgreSQL, Redis, or any other service that your integration tests need — without mocking — using the same Docker images you would use in production.
jobs: integration-tests: runs-on: ubuntu-latest services: postgres: image: postgres:16 env: POSTGRES_USER: testuser POSTGRES_PASSWORD: testpass POSTGRES_DB: testdb ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 redis: image: redis:7 ports: - 6379:6379 steps: - uses: actions/checkout@v4 - name: Run integration tests run: ./gradlew integrationTest env: DB_URL: jdbc:postgresql://localhost:5432/testdb DB_USER: testuser DB_PASS: testpass REDIS_URL: redis://localhost:6379
A few important details:
- Health checks via
options: --health-cmd ...ensure GitHub waits for the service to be ready before steps begin. Without this your tests may start before PostgreSQL finishes initialising. - Port mapping: the service is accessible from steps at
localhost:<host-port>. The host port and container port do not need to match but must be mapped inports:. - Container jobs: if your job itself runs inside a container (
container:key), services are accessible by the service label name (e.g.postgres:5432) rather thanlocalhost, because Docker networking uses the service name as DNS. - Services are only supported on GitHub-hosted Linux runners and self-hosted Linux runners with Docker available.
More Related questions...