.gitlab-ci mysql service in Django

I’m learning to use Gitlab CI and I’m trying to configure .gitlab-ci file to run CI into my Django project.

  • I have the following .gitlab-ci file:
stages:
    - test
 
variables:
    MYSQL_DATABASE: $DB_NAME
    MYSQL_USER: $DB_USER
    MYSQL_PASSWORD: $DB_PASSWORD

services:
    - mysql:8.0

test: 
    image: alpine:3.13
    stage: test
    script:
        - ...(up the app)...
  • I have configured the environment variables in the gitlab (Settings → CI/CD → Variables), e.g:
DB_HOST=mysql
  • And I have the following DB configuration in my settings.py file:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': getenv('DB_NAME'),
        'USER': getenv('DB_USER'),
        'PASSWORD': getenv('DB_PASSWORD'),
        'HOST': getenv('DB_HOST'),
        'PORT': getenv('DB_PORT'),
        'TEST' : {
            'NAME' : f"test_{getenv('DB_NAME')}",
        }
    }
}

When I run this, all the installation is successfully but at moment to run test I have the following error:

django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'mysql' (-2)")

Why it happens if in Gitlab Documentation said that if I use the mysql services it’s the host that I need to configure?

It was my mistake. I read the logs - although they were extensive - and I’ve found the following lines:

2021-04-11T00:04:33.635793560Z     You need to specify one of the following:
2021-04-11T00:04:33.635798376Z     - MYSQL_ROOT_PASSWORD
2021-04-11T00:04:33.635802359Z     - MYSQL_ALLOW_EMPTY_PASSWORD
2021-04-11T00:04:33.635805957Z     - MYSQL_RANDOM_ROOT_PASSWORD

It’s neccessary - of course - predefine the variable with the MySQL root password, without it the service can’t run.

We need at least one of the following variables to run the service:

- MYSQL_ROOT_PASSWORD
- MYSQL_ALLOW_EMPTY_PASSWORD
- MYSQL_RANDOM_ROOT_PASSWORD

I’ve changed my gitlab-ci file in the variables section and changed the directives by the following:

variables:
    MYSQL_DATABASE: $DB_NAME
    MYSQL_USER: $DB_USER
    MYSQL_PASSWORD: $DB_PASSWORD
    MYSQL_HOST: $DB_HOST
    MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD

And then I’ve exported the DB_ROOT_PASSWORD variable inside CI/CD configuration (Settings → CI/CD → Variables) and it worked.