Ravindra BagaleCourses & study guides मराठी

Chapter 92: GitLab CI Deep Dive

DevOps

92.8 Services — a real database for tests

Story (fictional teaching scenario). At a fictional hotel-booking company in Udaipur, tests used a fake in-memory database and passed, but production on PostgreSQL failed on a date query. Chen from Taipei added a service: a PostgreSQL container that starts next to the test job, only for that job. Now tests run against the same kind of database as production, and the container is thrown away afterwards.

A service container (like postgres) starts beside the job, is reachable by a host name, and is removed after the job.
A service container (like postgres) starts beside the job, is reachable by a host name, and is removed after the job.

Why

Testing against the real kind of database catches bugs that fakes hide.

What

  • services — Extra containers started for a job, like a database or cache.
  • alias — The host name the job uses to reach the service. By default it comes from the image name, like postgres.
  • Service variables — Settings the service image reads, like POSTGRES_DB and POSTGRES_PASSWORD.
  • Services need a runner with the Docker or Kubernetes executor.

How

  1. Add the service image under services:.
  2. Set the variables the image expects.
  3. Connect from your tests to the alias host name.
  4. Use a throwaway test password only; it is not a real secret because the database lives for minutes.

Example 1: PostgreSQL for one job

db-test:
  image: python:3.13-slim
  services:
    - name: postgres:16
      alias: db
  variables:
    POSTGRES_DB: "booking_test"
    POSTGRES_USER: "tester"
    POSTGRES_PASSWORD: "throwaway-test-only"
    DATABASE_URL: "postgresql://tester:throwaway-test-only@db:5432/booking_test"
  script:
    - pip install psycopg[binary]
    - python -c "import psycopg, os; c = psycopg.connect(os.environ['DATABASE_URL']); print(c.execute('select 1').fetchone())"

Line by line: services: starts postgres:16 with the host name db. The three POSTGRES_ variables tell the image to create a database and user. DATABASE_URL is how the test code finds it. The script installs a driver and runs one query. The password is a throwaway value for a database that exists only during this job.

Output (illustrative — pipeline not run)

$ python -c "import psycopg, os; ..."
(1,)
Job succeeded

What it means: The job reached the database at host db and got the answer (1,). The image tags are examples.

Ravindra Bagale's Tip

Services are for tests. Never point a CI test job at a shared or production database.

Did you understand? Let us try it once more.