How can I wait for the container to be healthy in GitHub action?

Viewed 1871

I am using GitHub action to do some automation test and my application was developed in docker.

name: Docker Image CI

on:
  push:
    branches: [ master]
  pull_request:
    branches: [ master]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - name: Build the Docker image
      run: docker-compose build

    - name: up mysql and apache container runs
      run: docker-compose up -d 

    - name: install dependencies
      run: docker exec  myapp php composer.phar install
  
    - name: show running container
      run: docker ps 


    - name: run unit test
      run: docker exec  myapp ./vendor/bin/phpunit 

At the step 'show running container', I can see that all the containers are running but for the MySQL, the status is (health: starting). Thus, my unit test cases all failed as it requires a connection to MySQL. So may I know if there is a way to start the unit case only when the MySQL container's status is healthy?

4 Answers

I would like to offer a solution, not a smart one but it requires minimum configuration and ready to go, just use the GitHub Action for Sleeping.

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Sleep for 30 seconds
      uses: jakejarvis/wait-action@master
      with:
        time: '30s'

Assumption: your Mysql server will be up and running in 30s.

As the documentation states:

To handle this, design your application to attempt to re-establish a connection to the database after a failure. If the application retries the connection, it can eventually connect to the database.

If you can't implement this at the moment, you can write some simple script that will indefinitely try a simple statement on the database. Once the script succeed you exit loop and start your unit tests. Check the documentation link I've provided, you'll find there an example of such script (wait-for-it.sh).

You can use thegabriele97/dockercompose-health-action

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Check services healthiness
        uses: thegabriele97/dockercompose-health-action@main
        with:
          timeout: '60'
          workdir: 'src'

As stated in documentation:

On Linux and macOS runners, use the sleep command:

- name: Sleep for 30 seconds
  run: sleep 30s
  shell: bash

On Windows runners, use the Start-Sleep command:

- name: Sleep for 30 seconds
  run: Start-Sleep -s 30
  shell: powershell
Related