GitHub Actionsのservice containersでCI実行時にMySQLコンテナを動かす

概要

GitHub Actionsのservice containersという機能を使うと、CI上でコンテナを動かすことができる。
ユースケースとしては統合テストや、マイグレーションテストが想定される。

About service containers - GitHub Docs

.github/workflows/test.yaml

name: MySQL Service Example
on: [push]

jobs:
  runner-job:
    runs-on: ubuntu-latest

    services:
      mysql:
        image: mysql
        env:
          MYSQL_ROOT_PASSWORD: pass
          MYSQL_DATABASE: test
        options: >-
          --health-cmd="mysqladmin ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 3306:3306

    steps:
      - name: Check out repository code
        uses: actions/checkout@v2
      - name: Install dependencies
        run: npm ci
      - name: Connect to MySQL
        run: node index.js
        env:
          MYSQL_HOST: 127.0.0.1

index.js

const mysql = require("mysql2");

const test = async () => {
  const connection = await mysql.createConnection({
    host: process.env.MYSQL_HOST,
    user: "root",
    password: "pass",
    database: "test",
    port: 3306,
  });
  await connection.connect((err) => {
    if (err) {
      console.log(err);
      process.exit(0);
    } else {
      console.log("success");
      process.exit(0);
    }
  });
};
test();

結果

Run node index.js
  node index.js
  shell: /usr/bin/bash -e {0}
  env:
    MYSQL_HOST: 127.0.0.1
success

まとめ

service containersを使ってMySQLに接続するところまで確認した。
これでマイグレーションの差分確認やDB接続が必要なテストなどがCI上で実行できる。

参考

https://docs.github.com/en/actions/using-containerized-services/creating-postgresql-service-containers