GitLab CI/CD Multi-Image Service Example with Java Project

Jean Marc NTEPPJean Marc NTEPP
2 min read

GitLab offers a game-changing feature — the ability to integrate multiple images seamlessly. Curious how? Dive into the world of Services with our PostgreSQL experiment!

  • We build a Spring application that lets you create and retrieve Person objects stored in a Postgres database by using Spring Data REST. (Quick teaser, try it :)

  • Write a test for it using the Postgres service in a Gitlab/CI

Step 1: Crafting Our Spring Data REST

Let’s kick things off by building a Spring application that facilitates the creation and retrieval of Person objects stored in a database via Spring Data REST.

Person Entity Definition:

Spring Data REST Repository:

Application Properties:

Run it with: spring-boot:run

Test that the application is running:

Step 2: Create a simple Integration Test

In this step, we ensure that our application seamlessly connects to the database. We’re not just testing; we can save and read a person from our DB.

Step 3: Create the gitlab-ci.yaml

The pipeline will have 2 images:

  • The first one is Maven to build our Java project

  • The second is Postgres for our database instance

GitLab CI Configuration:

stages:          # List of stages for jobs, and their order of execution
 - build
 - test

variables:
 MAVEN_OPTS: -Dmaven.repo.local=.m2/repository
 POSTGRES_DB: $POSTGRES_DB
 POSTGRES_USER: $POSTGRES_USER
 POSTGRES_PASSWORD: $POSTGRES_PASSWORD
 POSTGRES_HOST_AUTH_METHOD: trust

image: maven:latest

default-postgres:
 services:
   - postgres
 image: postgres
 variables:
   PGPORT: "5432"

 script:
   # official way to provide password to psql: http://www.postgresql.org/docs/9.3/static/libpq-envars.html
   - export PGPASSWORD=$POSTGRES_PASSWORD
   - psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT 'OK' AS status;"


build-job:       # This job runs in the build stage, which runs first.
 stage: build
 script:
   - echo "POSTGRES_DB is $POSTGRES_DB"
   - echo "Compiling the code..."
   - mvn compile

unit-test-job:   # This job runs in the test stage.
 stage: test    # It only starts when the job in the build stage completes successfully.
 services:
   - postgres
 script:
   - echo "Running unit tests..."
   - mvn clean test

Witness the magic unfold with our services section initializing the PostgreSQL database, paving the way for the unit test phase where the PostgreSQL service shines.

properties for test

Step 4: Run the Pipeline

Resources:

I am a software engineer, passionate about AI and Cloud Architecture. You can find more information about me on LinkedIn.

1
Subscribe to my newsletter

Read articles from Jean Marc NTEPP directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jean Marc NTEPP
Jean Marc NTEPP