Skip to main content

Redisサービスコンテナの作成

サービスコンテナを使って、ワークフロー中でRedisのクライアントを作成できます。 このガイドでは、コンテナで実行されるジョブか、ランナーマシン上で直接実行されるジョブのためのRedisサービスの作成例を紹介します。

はじめに

このガイドでは、Docker Hub の redis イメージを使ってサービスコンテナを設定するワークフローの例を紹介します。 このワークフローは、Redisのクライアントを作成してクライアントにデータを展開するスクリプトを実行します。 Redisクライアントを作成して展開するワークフローをテストするために、このスクリプトはクライアントのデータをコンソールに出力します。

注: ワークフローが Docker コンテナー アクション、ジョブ コンテナーあるいはサービス コンテナーを使うなら、Linux のランナーを使う必要があります。

  • GitHubホストランナーを使うなら、Ubuntuランナーを使わなければなりません。
  • セルフホストランナーを使っているなら、ランナーとしてLinuxマシンを使い、Dockerをインストールしておかなければなりません。

前提条件

GitHub Actionsとのサービスコンテナの動作と、ジョブを直接ランナー上で動作させる場合とコンテナ内で動作させる場合のネットワーキングの差異について、親しんでおいてください。 詳しくは、「サービスコンテナについて」を参照してください。

YAML、GitHub Actionsの構文、Redisの基本な理解があれば役立つかも知れません。 詳細については、次を参照してください。

コンテナ内でのジョブの実行

ジョブをコンテナ内で実行するように設定すれば、ジョブとサービスコンテナ間のネットワーク設定が単純になります。 同じユーザ定義ブリッジネットワーク上にあるDockerコンテナは、すべてのポートを互いに公開するので、サービスコンテナのポートをDockerホストにマップする必要がありません。 ワークフロー中で設定したラベルを使って、ジョブコンテナからサービスコンテナにアクセスできます。

このワークフロー ファイルをリポジトリの .github/workflows ディレクトリにコピーして、必要に応じて修正できます。

YAML
name: Redis container example
on: push

jobs:
  # Label of the container job
  container-job:
    # Containers must run in Linux based operating systems
    runs-on: ubuntu-latest
    # Docker Hub image that `container-job` executes in
    container: node:10.18-jessie

    # Service containers to run with `container-job`
    services:
      # Label used to access the service container
      redis:
        # Docker Hub image
        image: redis
        # Set health checks to wait until redis has started
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      # Downloads a copy of the code in your repository before running CI tests
      - name: Check out repository code
        uses: actions/checkout@v4

      # Performs a clean installation of all dependencies in the `package.json` file
      # For more information, see https://docs.npmjs.com/cli/ci.html
      - name: Install dependencies
        run: npm ci

      - name: Connect to Redis
        # Runs a script that creates a Redis client, populates
        # the client with data, and retrieves data
        run: node client.js
        # Environment variable used by the `client.js` script to create a new Redis client.
        env:
          # The hostname used to communicate with the Redis service container
          REDIS_HOST: redis
          # The default Redis port
          REDIS_PORT: 6379

コンテナジョブの設定

このワークフローは、node:10.18-jessie コンテナーで実行され、ubuntu-latest GitHub ホステッド ランナーをコンテナーの Docker ホストとして使用するジョブを構成します。 node:10.18-jessie コンテナーの詳細については、Docker Hub のノード イメージを参照してください。

ワークフローは、redis ラベルを使用してサービス コンテナーを構成します。 すべてのサービスはコンテナー内で実行しなければならないので、各サービスについてコンテナー image を指定する必要があります。 この例は redis コンテナー イメージを使用しており、サービスが動作していることを確認するためのヘルス チェック オプションが含まれます。 イメージ名にタグを追加してバージョンを指定します (例: redis:6)。 詳細については、Docker Hub の redis イメージを参照してください。

YAML
jobs:
  # Label of the container job
  container-job:
    # Containers must run in Linux based operating systems
    runs-on: ubuntu-latest
    # Docker Hub image that `container-job` executes in
    container: node:10.18-jessie

    # Service containers to run with `container-job`
    services:
      # Label used to access the service container
      redis:
        # Docker Hub image
        image: redis
        # Set health checks to wait until redis has started
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

コンテナー ジョブの手順の構成

ワークフローは以下のステップを実行します。

  1. ランナー上にリポジトリをチェックアウト
  2. 依存関係のインストール
  3. クライアントを作成するスクリプトの実行
YAML
steps:
  # Downloads a copy of the code in your repository before running CI tests
  - name: Check out repository code
    uses: actions/checkout@v4

  # Performs a clean installation of all dependencies in the `package.json` file
  # For more information, see https://docs.npmjs.com/cli/ci.html
  - name: Install dependencies
    run: npm ci

  - name: Connect to Redis
    # Runs a script that creates a Redis client, populates
    # the client with data, and retrieves data
    run: node client.js
    # Environment variable used by the `client.js` script to create a new Redis client.
    env:
      # The hostname used to communicate with the Redis service container
      REDIS_HOST: redis
      # The default Redis port
      REDIS_PORT: 6379

client.js スクリプトは、クライアントを作成するための環境変数 REDIS_HOSTREDIS_PORT を探します。 ワークフローは、これら 2 つの環境変数を "Redis に接続する" ステップの一部として設定し、client.js スクリプトから利用できるようにします。 スクリプトの詳細については、「Redis サービス コンテナーのテスト」を参照してください。

Redis サービスのホスト名は、ワークフロー中で設定されたラベルで、ここでは redis です。 同じユーザー定義ブリッジネットワーク上のDockerコンテナは、デフォルトですべてのポートをオープンするので、サービスコンテナにはデフォルトのRedisのポートである6379でアクセスできます。

ランナーマシン上で直接のジョブの実行

ランナーマシン上で直接ジョブを実行する場合、サービスコンテナ上のポートをDockerホスト上のポートにマップしなければなりません。 Docker ホストからサービス コンテナーへは、localhost と Docker ホストのポート番号を使ってアクセスできます。

このワークフロー ファイルをリポジトリの .github/workflows ディレクトリにコピーして、必要に応じて修正できます。

YAML
name: Redis runner example
on: push

jobs:
  # Label of the runner job
  runner-job:
    # You must use a Linux environment when using service containers or container jobs
    runs-on: ubuntu-latest

    # Service containers to run with `runner-job`
    services:
      # Label used to access the service container
      redis:
        # Docker Hub image
        image: redis
        # Set health checks to wait until redis has started
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          # Maps port 6379 on service container to the host
          - 6379:6379

    steps:
      # Downloads a copy of the code in your repository before running CI tests
      - name: Check out repository code
        uses: actions/checkout@v4

      # Performs a clean installation of all dependencies in the `package.json` file
      # For more information, see https://docs.npmjs.com/cli/ci.html
      - name: Install dependencies
        run: npm ci

      - name: Connect to Redis
        # Runs a script that creates a Redis client, populates
        # the client with data, and retrieves data
        run: node client.js
        # Environment variable used by the `client.js` script to create
        # a new Redis client.
        env:
          # The hostname used to communicate with the Redis service container
          REDIS_HOST: localhost
          # The default Redis port
          REDIS_PORT: 6379

ランナージョブの設定

この例では、Docker ホストとして ubuntu-latest GitHub ホストテッド ランナーを使用します。

ワークフローは、redis ラベルを使用してサービス コンテナーを構成します。 すべてのサービスはコンテナー内で実行しなければならないので、各サービスについてコンテナー image を指定する必要があります。 この例は redis コンテナー イメージを使用しており、サービスが動作していることを確認するためのヘルス チェック オプションが含まれます。 イメージ名にタグを追加してバージョンを指定します (例: redis:6)。 詳細については、Docker Hub の redis イメージを参照してください。

このワークフローはRedisサービスコンテナ上のポート6379をDockerホストにマップします。 ports キーワードについて詳しくは、「サービスコンテナについて」をご覧ください。

YAML
jobs:
  # Label of the runner job
  runner-job:
    # You must use a Linux environment when using service containers or container jobs
    runs-on: ubuntu-latest

    # Service containers to run with `runner-job`
    services:
      # Label used to access the service container
      redis:
        # Docker Hub image
        image: redis
        # Set health checks to wait until redis has started
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          # Maps port 6379 on service container to the host
          - 6379:6379

ランナー ジョブの手順の構成

ワークフローは以下のステップを実行します。

  1. ランナー上にリポジトリをチェックアウト
  2. 依存関係のインストール
  3. クライアントを作成するスクリプトの実行
YAML
steps:
  # Downloads a copy of the code in your repository before running CI tests
  - name: Check out repository code
    uses: actions/checkout@v4

  # Performs a clean installation of all dependencies in the `package.json` file
  # For more information, see https://docs.npmjs.com/cli/ci.html
  - name: Install dependencies
    run: npm ci

  - name: Connect to Redis
    # Runs a script that creates a Redis client, populates
    # the client with data, and retrieves data
    run: node client.js
    # Environment variable used by the `client.js` script to create
    # a new Redis client.
    env:
      # The hostname used to communicate with the Redis service container
      REDIS_HOST: localhost
      # The default Redis port
      REDIS_PORT: 6379

client.js スクリプトは、クライアントを作成するための環境変数 REDIS_HOSTREDIS_PORT を探します。 ワークフローは、これら 2 つの環境変数を "Redis に接続する" ステップの一部として設定し、client.js スクリプトから利用できるようにします。 スクリプトの詳細については、「Redis サービス コンテナーのテスト」を参照してください。

ホスト名は、localhost または 127.0.0.1 です。

Redisサービスコンテナのテスト

ワークフローを以下のスクリプトでテストできます。このスクリプトはRedisクライアントを作成し、いくつかのプレースホルダーデータをクライアントに展開します。 そしてこのスクリプトは、Redisクライアント内に保存された値をターミナルに出力します。 スクリプトには好きな言語を使えますが、この例では Node.js と npm モジュールの redis を使っています。 詳しくは、「npm redis モジュール」を参照してください。

client.js を修正して、ワークフローで必要な Redis の操作を含めることができます。 この例では、スクリプトはRedisクライアントのインスタンスを作成し、プレースホルダーデータを追加し、そしてそのデータを取り出します。

以下のコードを使用して、リポジトリに client.js という名前の新しいファイルを追加してください。

JavaScript
const redis = require("redis");

// Creates a new Redis client
// If REDIS_HOST is not set, the default host is localhost
// If REDIS_PORT is not set, the default port is 6379
const redisClient = redis.createClient({
  url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`
});

redisClient.on("error", (err) => console.log("Error", err));

(async () => {
  await redisClient.connect();

  // Sets the key "octocat" to a value of "Mona the octocat"
  const setKeyReply = await redisClient.set("octocat", "Mona the Octocat");
  console.log("Reply: " + setKeyReply);
  // Sets a key to "species", field to "octocat", and "value" to "Cat and Octopus"
  const SetFieldOctocatReply = await redisClient.hSet("species", "octocat", "Cat and Octopus");
  console.log("Reply: " + SetFieldOctocatReply);
  // Sets a key to "species", field to "dinotocat", and "value" to "Dinosaur and Octopus"
  const SetFieldDinotocatReply = await redisClient.hSet("species", "dinotocat", "Dinosaur and Octopus");
  console.log("Reply: " + SetFieldDinotocatReply);
  // Sets a key to "species", field to "robotocat", and "value" to "Cat and Robot"
  const SetFieldRobotocatReply = await redisClient.hSet("species", "robotocat", "Cat and Robot");
  console.log("Reply: " + SetFieldRobotocatReply);

  try {
    // Gets all fields in "species" key
    const replies = await redisClient.hKeys("species");
    console.log(replies.length + " replies:");
    replies.forEach((reply, i) => {
        console.log("    " + i + ": " + reply);
    });
    await redisClient.quit();
  }
  catch (err) {
    // statements to handle any exceptions
  }
})();

このスクリプトでは、host パラメーターと port パラメーターを受け取る createClient メソッドを使用して新しい Redis クライアントが作成されます。 このスクリプトでは、クライアントの IP アドレスとポートを設定するために、REDIS_HOST 環境変数と REDIS_PORT 環境変数が使用されます。 hostport が定義されていない場合、既定のホストは localhost であり、既定のポートは 6379 です。

このスクリプトでは、set メソッドと hset メソッドを使用し、データベースに一部のキー、フィールド、値を入力します。 Redisデータベースがデータを含んでいることを確認するために、スクリプトはデータベースの内容をコンソールログに出力します。

このワークフローを実行すると、"Connect to Redis"ステップで以下のように出力され、Redisのクライアントが作成され、データが追加されたことが確認できます。

Reply: OK
Reply: 1
Reply: 1
Reply: 1
3 replies:
    0: octocat
    1: dinotocat
    2: robotocat