如何在 GitHub 操作中等待容器健康?

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

我正在使用 GitHub 操作进行一些自动化测试,我的应用程序是在 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 

在第 'show running container' 步,我可以看到所有容器都是 运行 但对于 MySQL,状态是(健康:正在启动)。因此,我的单元测试用例都失败了,因为它需要连接到 MySQL。那么我可以知道是否有一种方法可以仅在 MySQL 容器的状态正常时启动单元案例?

documentation 所述:

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.

如果你现在不能实现这个,你可以写一些简单的脚本,无限期地在数据库上尝试一个简单的语句。一旦脚本成功退出循环并开始单元测试。查看我提供的文档 link,您会在那里找到此类脚本的示例 (wait-for-it.sh)。

我想提供一个解决方案,不是一个聪明的解决方案,但它需要最低配置并准备就绪,只需使用 GitHub 睡眠操作。

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

假设:您的 Mysql 服务器将在 30 秒内启动并 运行。

您可以使用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'