20
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Github Actionsでのコンテナを用いたサーバー死活チェック

Last updated at Posted at 2023-12-12

はじめに

ライブラリのバージョンが上がったことで、ビルドは成功するのに起動時にエラーが出ることがありました。
手動でいちいち動作確認したくないので、Github Actionsでサーバが起動するかチェックするように設定します。

チェックの流れ

githubにプッシュをしたタイミングで指定したコンテナが存在するかどうかチェック

docker inspect を使ってコンテナが起動しているかステータスをチェック

起動している場合成功、失敗している場合5回リトライ処理を設ける。インターバルは5秒とします。

リトライ回数を超えた場合失敗してエラーコードを返します。

※エラーの場合
以下のようにexitして失敗として処理します。
image.png

GitHub Actionsの設定

name: ci

on:
  push:
    branches: [develop]
  

・・・省略・・・


      - name: Run Docker Container
        run: |
          docker-compose up -d

      - name: Check Docker Container
        run: |
          # コンテナ名指定("container1" "container2" "container3"...)
          container_names=("invoice-maker")

          # タイムアウトまでの待機時間(秒)
          timeout_seconds=300
          # リトライ回数
          max_retries=5
          # インターバル(秒)
          retry_interval=5
          # タイムアウトを計算
          end_time=$((SECONDS+timeout_seconds))
            
          #コンテナ存在チェック
          for container_name in "${container_names[@]}"; do
            if ! docker ps -a --format '{{.Names}}' | grep -q "$container_name"; then
            echo "$container_name does not exist."
            exit 1
            fi

            echo "Container: $container_name";
            sleep $retry_interval
            retries=0

            while [ $SECONDS -lt $end_time ]; do
              # Dockerコンテナの状態を確認
              if docker inspect -f '{{.State.Status}}' $container_name | grep -q "running"; then
                echo $container_name "has started successfully!"
                break
              else
                retries=$((retries+1))
                echo "Waiting for Docker container to start...$retries"
                sleep $retry_interval
              fi
              # リトライ回数を超えた場合は失敗として終了
              if [ $retries -ge $max_retries ]; then
                echo "Failed to start Docker container after $max_retries retries."
                exit 1
              fi
            done
          done

まとめ

リポジトリはGithubのDependabotを使ってライブラリのバージョン修正を自動で行っていたため、今回の設定をすることで自動バージョンアップ後にもサーバーが動くかどうか、手動で確認する手間を省けるという利点があります。

20
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?