Configuring Services in GitLab CI Jobs
How to configure GitLab CI services for databases, caches, and Docker-in-Docker. Covers service aliases, health checks, and environment variables.
Detailed Explanation
Using Services in GitLab CI
Services in GitLab CI are Docker containers that run alongside your job container. They provide dependencies like databases and caches without Docker Compose.
PostgreSQL Service
test_with_postgres:
stage: test
image: node:20-alpine
services:
- name: postgres:16-alpine
alias: db
variables:
POSTGRES_DB: testdb
POSTGRES_USER: runner
POSTGRES_PASSWORD: secret
DATABASE_URL: "postgresql://runner:secret@db:5432/testdb"
script:
- npm ci
- npm run test:integration
Redis Service
test_with_redis:
stage: test
image: python:3.12-slim
services:
- name: redis:7-alpine
alias: cache
variables:
REDIS_URL: "redis://cache:6379"
script:
- pip install -r requirements.txt
- pytest tests/integration/
Multiple Services
integration:
stage: test
image: node:20-alpine
services:
- name: postgres:16-alpine
alias: db
- name: redis:7-alpine
alias: cache
- name: elasticsearch:8.12.0
alias: search
variables:
POSTGRES_DB: testdb
POSTGRES_USER: runner
POSTGRES_PASSWORD: secret
How Service Networking Works
Services are linked to the job container via Docker networking. The alias becomes the hostname. Without an alias, the hostname is derived from the image name: postgres:16-alpine becomes postgres.
Service Variables
Environment variables set in the variables section are passed to both the job container and all service containers. This is how you configure databases (e.g., POSTGRES_DB) — the Postgres service container reads these variables during startup.
Use Case
Use services when you need a single database or cache alongside your tests. For more complex multi-container setups, consider Docker Compose instead.