Can't connect to MySQL service in a CI job

I am trying to create a job to test our Laravel application, which needs a MySQL service running in order to be able to work.

The issue is that for some reason I cannot log in with the root user using the credentials I set up the MySQL service with, so I am getting this error:

ERROR 1045 (28000): Access denied for user 'root'@'172.17.0.3' (using password: YES)

The code to set up the CI job is this:

pest:
  stage: test
  image: <our image with what we need>
  interruptible: true
  services:
    - name: mysql/mysql-server:8.0
      alias: mysql
      command: ['--default-authentication-plugin=mysql_native_password']
  variables:
    MYSQL_ROOT_PASSWORD: password
    MYSQL_USER: sail
    MYSQL_PASSWORD: password
    MYSQL_DATABASE: laravel
    MYSQL_HOST: mysql
  script:
    - |
      mysql --host=${MYSQL_HOST} --user=root --password=${MYSQL_ROOT_PASSWORD} <<-EOSQL
        CREATE DATABASE IF NOT EXISTS testing;
        GRANT ALL PRIVILEGES ON \`testing%\`.* TO '${MYSQL_USER}'@'%';
      EOSQL
    - php artisan migrate:fresh --seed
    - ./vendor/bin/pest --coverage --coverage-cobertura coverage/cobertura-coverage.xml --log-junit coverage/junit.xml
  coverage: '/^\s*Total:\s*\d+.\d+\%/'
  artifacts:
    when: always
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage/cobertura-coverage.xml
      junit:
        - coverage/junit.xml
  needs:
    - job: composer
      artifacts: true
    - job: yarn-build
      artifacts: true

Turns out the fix was simple. From the MySQL docs:

MYSQL_ROOT_HOST: By default, MySQL creates the 'root'@'localhost' account. This account can only be connected to from inside the container as described in Connecting to MySQL Server from within the Container. To allow root connections from other hosts, set this environment variable. […]

So the fix was to simply add the variable I was missing:

pest:
  ...
  variables:
    ...
    MYSQL_ROOT_HOST: '%'

And it worked!

1 Like