Docker Compose Test
Setting up test environments with Docker Compose (DB, Redis, etc.) and running integration tests
An example of using Docker Compose to spin up external services such as databases and caches, then running integration tests.
Full Code
name: compose-integration-test
triggers:
push:
branches: [main, develop]
change_request:
branches: [main]
jobs:
integration-test:
# Declare Docker service for Docker Compose usage
services:
- docker
steps:
# 1. Source code checkout
- name: checkout
uses: "collabops/checkout@v2"
with:
repo-url: "https://<collabops-host>/<workspace>/<repository>.git"
# 2. Start test services (DB + Redis)
# Run in background with docker compose up -d
- name: start-services
image: docker:27.5-cli
run: |
cd /workspace/source
docker compose up -d db redis
# Wait for services to be ready
echo "Waiting for services..."
sleep 5
docker compose ps
# 3. Run integration tests
- name: run-tests
image: python:3.12
run: |
cd /workspace/source
pip install -r requirements.txt
pytest tests/integration/ -v --tb=short
env:
DATABASE_URL: "postgresql://test:test@db:5432/testdb"
REDIS_URL: "redis://redis:6379"
# 4. Stop services and clean up
- name: stop-services
image: docker:27.5-cli
run: |
cd /workspace/source
docker compose down -v # Clean up including volumesdocker-compose.yml Example
Assuming the following file exists at the project root:
# docker-compose.yml (project file)
services:
db:
image: postgres:16
environment:
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
ports:
- "5432:5432"
redis:
image: redis:7-alpine
ports:
- "6379:6379"Key Points
Enabling the Docker service with services: [docker] allows you to use docker compose commands.
In the test Step, service names (db, redis) are used as hostnames.
docker compose down -v cleans up including volumes, so it doesn't affect subsequent runs.