Integration Testing with Docker Compose in GitLab CI
Run integration tests with Docker Compose in GitLab CI. Set up multi-container test environments with databases, message queues, and your application.
Detailed Explanation
Integration Testing with Docker Compose
When your application depends on external services (databases, caches, message queues), Docker Compose provides a reliable way to spin up the entire stack for integration testing.
Pipeline Configuration
stages:
- test
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: /certs
integration_test:
stage: test
image: docker:24
services:
- name: docker:24-dind
alias: docker
before_script:
- apk add --no-cache docker-compose
- docker-compose -f docker-compose.test.yml up -d
- sleep 10
script:
- docker-compose -f docker-compose.test.yml exec -T app npm run test:integration
after_script:
- docker-compose -f docker-compose.test.yml logs
- docker-compose -f docker-compose.test.yml down -v
artifacts:
paths:
- test-results/
expire_in: 7 days
when: always
docker-compose.test.yml Example
version: "3.8"
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: testdb
POSTGRES_USER: test
POSTGRES_PASSWORD: test
redis:
image: redis:7-alpine
app:
build: .
depends_on:
- db
- redis
environment:
DATABASE_URL: postgresql://test:test@db:5432/testdb
REDIS_URL: redis://redis:6379
Key Considerations
after_script for cleanup: The after_script always runs, even if the test fails. This ensures containers are stopped and logs are captured for debugging.
when: always on artifacts: Test results are uploaded even on failure, so you can inspect what went wrong.
-T flag on exec: The -T flag disables pseudo-TTY allocation, which is necessary in CI environments where no TTY is available.
Health checks: For production pipelines, replace the sleep 10 with proper health check polling to avoid flaky tests.
Use Case
Use for applications that require integration testing with real databases, caches, or message brokers. Common for microservice architectures where individual services need to be tested against their dependencies.