Cornel Verster
Cornel Verster

Reputation: 1783

Laravel Gitlab CI/CD MySQL connection

I'm trying to test my Laravel / InertiaJS / Vue / Vite project as part of my Gitlab CI/CD pipeline. I have 5 steps in my pipeline:

  1. build composer - install composer dependencies
  2. build npm - install and build npm
  3. connect mysql - test that the mysql connection works
  4. setup app - try to run php artisan migrate
  5. test - run pest tests

Step 3 passes, and I can run the following command with success:

echo "SELECT 'OK';" | mysql --user=root --password="$MYSQL_ROOT_PASSWORD" --host=mysql "$MYSQL_DATABASE"

But, step 4 fails when I try to execute php artisan migrate with the following error:

SQLSTATE[HY000] [2002] Connection refused (Connection: mysql, SQL: select *  
   from information_schema.tables where table_schema = parmt and table_name =  
   migrations and table_type = 'BASE TABLE')

Here is my .gitlab-ci.yml file:

image: lorisleiva/laravel-docker:latest

services:
  - mysql:latest

variables:
  CI_COMMIT_REF_SLUG: main
  MYSQL_DATABASE: [db]
  MYSQL_ROOT_PASSWORD: [pw]

stages:
  - build composer
  - build npm
  - connect mysql
  - setup app
  - test

composer:
  
  stage: build composer
  script:
    - composer install --no-interaction --prefer-dist --optimize-autoloader
    - cp .env.example .env
    - php artisan key:generate

  artifacts:
    expire_in: 1 month
    paths:
      - vendor/
      - .env

  cache:
    key: ${CI_COMMIT_REF_SLUG}-composer
    paths:
      - vendor/

npm:

  stage: build npm

  dependencies:
    - composer

  cache:
    key: ${CI_COMMIT_REF_SLUG}-npm
    paths:
      - node_modules/

  script:
    - npm install
    - npm run build

  artifacts:
    expire_in: 1 month
    paths:
      - node_modules/
      - public/css/
      - public/js/

connect:
  stage: connect mysql
  image: mysql
  script:
    - echo "SELECT 'OK';" | mysql --user=root --password="$MYSQL_ROOT_PASSWORD" --host=mysql "$MYSQL_DATABASE"

app:
  stage: setup app
  dependencies:
    - composer
    - npm

  script:
    - cat .env # this is just to check I've got a valid setup
    - php artisan config:clear
    - php artisan optimize
    - php artisan migrate

pest:
  stage: test
  dependencies:
    - composer
    - npm
    - connect
    - app
  script:
    - php artisan optimize
    - php artisan test --colors=never --coverage-text

Previously, I was able to run the migration, but then found that in all of my Pest tests I got this same error, and thus none of them ran.

Can someone tell me how I should set this up to work?

Upvotes: 1

Views: 427

Answers (1)

Ruan Pépe
Ruan Pépe

Reputation: 5

To be sure about the solution, also take a look in your docker-compose.yml and in your .env.example. I believe the mistake is in your .env.example. If the DB_HOST is set like localhost or 127.0.0.1, change it to mysql.

Check this.

Upvotes: 0

Related Questions