{"meta":{"title":"PostgreSQLサービスコンテナの作成","intro":"ワークフローで利用するPostgreSQLサービスコンテナを作成できます。 このガイドでは、コンテナで実行されるジョブか、ランナーマシン上で直接実行されるジョブのためのPostgreSQLサービスの作成例を紹介します。","product":"GitHub Actions","breadcrumbs":[{"href":"/ja/actions","title":"GitHub Actions"},{"href":"/ja/actions/tutorials","title":"チュートリアル"},{"href":"/ja/actions/tutorials/use-containerized-services","title":"コンテナー化されたサービスを使用する"},{"href":"/ja/actions/tutorials/use-containerized-services/create-postgresql-service-containers","title":"PostgreSQL サービス コンテナーを作成する"}],"documentType":"article"},"body":"# PostgreSQLサービスコンテナの作成\n\nワークフローで利用するPostgreSQLサービスコンテナを作成できます。 このガイドでは、コンテナで実行されるジョブか、ランナーマシン上で直接実行されるジョブのためのPostgreSQLサービスの作成例を紹介します。\n\n## はじめに\n\nこのガイドでは、Docker Hub `postgres` イメージを使用してサービス コンテナーを構成するワークフローの例を示します。 ワークフローの実行スクリプトは、PostgreSQL サービスに接続し、テーブルを作成してから、データを入力します。 ワークフローが PostgreSQL テーブルを作成してデータを入力することをテストするために、スクリプトはテーブルからコンソールにデータを出力します。\n\n> \\[!NOTE]\n> ワークフローで Docker コンテナー アクション、ジョブ コンテナー、またはサービス コンテナーが使われる場合は、Linux ランナーを使う必要があります。\n>\n> * GitHubホストランナーを使うなら、Ubuntuランナーを使わなければなりません。\n> * セルフホストランナーを使っているなら、ランナーとしてLinuxマシンを使い、Dockerをインストールしておかなければなりません。\n\n## 前提条件\n\nデータ再利用可能なアクション.サービスコンテナ前提条件 %}\n\nYAML、GitHub Actionsの構文、PosgreSQLの基本な理解があれば役立つかも知れません。 詳細については、以下を参照してください:\n\n* [ワークフローの書き込み](/ja/actions/learn-github-actions)\n* PostgreSQL ドキュメントの [PostgreSQL チュートリアル](https://www.postgresqltutorial.com/)\n\n## コンテナ内でのジョブの実行\n\nジョブをコンテナ内で実行するように設定すれば、ジョブとサービスコンテナ間のネットワーク設定が単純になります。 同じユーザ定義ブリッジネットワーク上にあるDockerコンテナは、すべてのポートを互いに公開するので、サービスコンテナのポートをDockerホストにマップする必要がありません。 ワークフロー中で設定したラベルを使って、ジョブコンテナからサービスコンテナにアクセスできます。\n\nこのワークフロー ファイルをリポジトリの `.github/workflows` ディレクトリにコピーして、必要に応じて修正できます。\n\n```yaml copy\nname: PostgreSQL service example\non: push\n\njobs:\n  # Label of the container job\n  container-job:\n    # Containers must run in Linux based operating systems\n    runs-on: ubuntu-latest\n    # Docker Hub image that `container-job` executes in\n    container: node:20-bookworm-slim\n\n    # Service containers to run with `container-job`\n    services:\n      # Label used to access the service container\n      postgres:\n        # Docker Hub image\n        image: postgres\n        # Provide the password for postgres\n        env:\n          POSTGRES_PASSWORD: postgres\n        # Set health checks to wait until postgres has started\n        options: >-\n          --health-cmd pg_isready\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n\n    steps:\n      # Downloads a copy of the code in your repository before running CI tests\n      - name: Check out repository code\n        uses: actions/checkout@v5\n\n      # Performs a clean installation of all dependencies in the `package.json` file\n      # For more information, see https://docs.npmjs.com/cli/ci.html\n      - name: Install dependencies\n        run: npm ci\n\n      - name: Connect to PostgreSQL\n        # Runs a script that creates a PostgreSQL table, populates\n        # the table with data, and then retrieves the data.\n        run: node client.js\n        # Environment variables used by the `client.js` script to create a new PostgreSQL table.\n        env:\n          # The hostname used to communicate with the PostgreSQL service container\n          POSTGRES_HOST: postgres\n          # The default PostgreSQL port\n          POSTGRES_PORT: 5432\n```\n\n### コンテナー内のジョブのランナー ジョブの構成\n\nこのワークフローは、`node:20-bookworm-slim` コンテナーで実行されるジョブを構成し、`ubuntu-latest`  GitHub ホステッド ランナーをコンテナーの Docker ホストとして使用するジョブを構成します。 `node:20-bookworm-slim` コンテナーの詳細については、Docker Hub の[ノード イメージ](https://hub.docker.com/_/node)を参照してください。\n\nこのワークフローは、`node:20-bookworm-slim` コンテナーで実行されるジョブを構成し、`ubuntu-latest`  GitHub ホステッド ランナーをコンテナーの Docker ホストとして使用するジョブを構成します。 `node:20-bookworm-slim` コンテナーの詳細については、Docker Hub の[ノード イメージ](https://hub.docker.com/_/node)を参照してください。\n\n```yaml copy\njobs:\n  # Label of the container job\n  container-job:\n    # Containers must run in Linux based operating systems\n    runs-on: ubuntu-latest\n    # Docker Hub image that `container-job` executes in\n    container: node:20-bookworm-slim\n\n    # Service containers to run with `container-job`\n    services:\n      # Label used to access the service container\n      postgres:\n        # Docker Hub image\n        image: postgres\n        # Provide the password for postgres\n        env:\n          POSTGRES_PASSWORD: postgres\n        # Set health checks to wait until postgres has started\n        options: >-\n          --health-cmd pg_isready\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n```\n\n### コンテナー内のジョブ手順を設定する方法\n\nワークフローは以下のステップを実行します。\n\n1. ランナー上にリポジトリをチェックアウト\n2. 依存関係のインストール\n3. クライアントを作成するスクリプトの実行\n\n```yaml copy\nsteps:\n  # Downloads a copy of the code in your repository before running CI tests\n  - name: Check out repository code\n    uses: actions/checkout@v5\n\n  # Performs a clean installation of all dependencies in the `package.json` file\n  # For more information, see https://docs.npmjs.com/cli/ci.html\n  - name: Install dependencies\n    run: npm ci\n\n  - name: Connect to PostgreSQL\n    # Runs a script that creates a PostgreSQL table, populates\n    # the table with data, and then retrieves the data.\n    run: node client.js\n    # Environment variable used by the `client.js` script to create\n    # a new PostgreSQL client.\n    env:\n      # The hostname used to communicate with the PostgreSQL service container\n      POSTGRES_HOST: postgres\n      # The default PostgreSQL port\n      POSTGRES_PORT: 5432\n```\n\nデータ 再利用可能アクションのPostgreSQL環境変数 %}\n\nPostgreSQL サービスのホスト名は、ワークフロー内で構成されたラベルです (ここでは `postgres`)。 同じユーザー定義ブリッジネットワーク上のDockerコンテナは、デフォルトですべてのポートをオープンするので、サービスコンテナにはデフォルトのPostgreSQLのポートである5432でアクセスできます。\n\n## ランナーマシン上で直接のジョブの実行\n\nランナーマシン上で直接ジョブを実行する場合、サービスコンテナ上のポートをDockerホスト上のポートにマップしなければなりません。 Docker ホストからサービス コンテナーへは、`localhost` と Docker ホストのポート番号を使ってアクセスできます。\n\nこのワークフロー ファイルをリポジトリの `.github/workflows` ディレクトリにコピーして、必要に応じて修正できます。\n\n```yaml copy\nname: PostgreSQL Service Example\non: push\n\njobs:\n  # Label of the runner job\n  runner-job:\n    # You must use a Linux environment when using service containers or container jobs\n    runs-on: ubuntu-latest\n\n    # Service containers to run with `runner-job`\n    services:\n      # Label used to access the service container\n      postgres:\n        # Docker Hub image\n        image: postgres\n        # Provide the password for postgres\n        env:\n          POSTGRES_PASSWORD: postgres\n        # Set health checks to wait until postgres has started\n        options: >-\n          --health-cmd pg_isready\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n        ports:\n          # Maps tcp port 5432 on service container to the host\n          - 5432:5432\n\n    steps:\n      # Downloads a copy of the code in your repository before running CI tests\n      - name: Check out repository code\n        uses: actions/checkout@v5\n\n      # Performs a clean installation of all dependencies in the `package.json` file\n      # For more information, see https://docs.npmjs.com/cli/ci.html\n      - name: Install dependencies\n        run: npm ci\n\n      - name: Connect to PostgreSQL\n        # Runs a script that creates a PostgreSQL table, populates\n        # the table with data, and then retrieves the data\n        run: node client.js\n        # Environment variables used by the `client.js` script to create\n        # a new PostgreSQL table.\n        env:\n          # The hostname used to communicate with the PostgreSQL service container\n          POSTGRES_HOST: localhost\n          # The default PostgreSQL port\n          POSTGRES_PORT: 5432\n```\n\n### ランナー マシンで直接ジョブのランナー ジョブを構成する\n\nこの例では、`ubuntu-latest`  GitHub でホストされる ランナーを Docker ホストとして使用します。\n\nactions/checkout\\@v5\n\nこのワークフローはPostgreSQLサービスコンテナ上のポート5432をDockerホストにマップします。\n`ports` キーワードについて詳しくは、「[Docker サービス コンテナーとの通信](/ja/actions/using-containerized-services/about-service-containers#mapping-docker-host-and-service-container-ports)」をご覧ください。\n\n```yaml copy\njobs:\n  # Label of the runner job\n  runner-job:\n    # You must use a Linux environment when using service containers or container jobs\n    runs-on: ubuntu-latest\n\n    # Service containers to run with `runner-job`\n    services:\n      # Label used to access the service container\n      postgres:\n        # Docker Hub image\n        image: postgres\n        # Provide the password for postgres\n        env:\n          POSTGRES_PASSWORD: postgres\n        # Set health checks to wait until postgres has started\n        options: >-\n          --health-cmd pg_isready\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n        ports:\n          # Maps tcp port 5432 on service container to the host\n          - 5432:5432\n```\n\n### ランナー マシンでジョブの手順を直接構成する\n\nワークフローは以下のステップを実行します。\n\n1. ランナー上にリポジトリをチェックアウト\n2. 依存関係のインストール\n3. クライアントを作成するスクリプトの実行\n\n```yaml copy\nsteps:\n  # Downloads a copy of the code in your repository before running CI tests\n  - name: Check out repository code\n    uses: actions/checkout@v5\n\n  # Performs a clean installation of all dependencies in the `package.json` file\n  # For more information, see https://docs.npmjs.com/cli/ci.html\n  - name: Install dependencies\n    run: npm ci\n\n  - name: Connect to PostgreSQL\n    # Runs a script that creates a PostgreSQL table, populates\n    # the table with data, and then retrieves the data\n    run: node client.js\n    # Environment variables used by the `client.js` script to create\n    # a new PostgreSQL table.\n    env:\n      # The hostname used to communicate with the PostgreSQL service container\n      POSTGRES_HOST: localhost\n      # The default PostgreSQL port\n      POSTGRES_PORT: 5432\n```\n\nデータ 再利用可能アクションのPostgreSQL環境変数 %}\n\nホスト名は、`localhost` または `127.0.0.1` です。\n\n## PostgreSQLサービスコンテナのテスト\n\n次のスクリプトを使用してワークフローをテストできます。このスクリプトは、PostgreSQL サービスに接続し、プレースホルダーデータを含む新しいテーブルを追加します。 そしてそのスクリプトは PostgreSQL テーブルに保存されている値をターミナルに出力します。 スクリプトには好きな言語を使えますが、この例では Node.js と npm モジュールの `pg` を使っています。 詳しくは、[npm pg モジュール](https://www.npmjs.com/package/pg)に関するページをご覧ください。\n\n```\n          _client.js_ を変更して、ワークフローで必要な任意の PostgreSQL 操作を含めることができます。 この例のスクリプトは、PostgreSQL サービスに接続し、`postgres` データベースにテーブルを追加し、プレースホルダー データをいくつか挿入してから、データを取得します。\n```\n\n以下のコードを使用して、リポジトリに *client.js* という名前の新しいファイルを追加してください。\n\n```javascript copy\nconst { Client } = require('pg');\n\nconst pgclient = new Client({\n    host: process.env.POSTGRES_HOST,\n    port: process.env.POSTGRES_PORT,\n    user: 'postgres',\n    password: 'postgres',\n    database: 'postgres'\n});\n\npgclient.connect();\n\nconst table = 'CREATE TABLE student(id SERIAL PRIMARY KEY, firstName VARCHAR(40) NOT NULL, lastName VARCHAR(40) NOT NULL, age INT, address VARCHAR(80), email VARCHAR(40))'\nconst text = 'INSERT INTO student(firstname, lastname, age, address, email) VALUES($1, $2, $3, $4, $5) RETURNING *'\nconst values = ['Mona the', 'Octocat', 9, '88 Colin P Kelly Jr St, San Francisco, CA 94107, United States', 'octocat@github.com']\n\npgclient.query(table, (err, res) => {\n    if (err) throw err\n});\n\npgclient.query(text, values, (err, res) => {\n    if (err) throw err\n});\n\npgclient.query('SELECT * FROM student', (err, res) => {\n    if (err) throw err\n    console.log(err, res.rows) // Print the data in student table\n    pgclient.end()\n});\n```\n\nこのスクリプトは、PostgreSQL サービスへの新しい接続を作成し、`POSTGRES_HOST` と `POSTGRES_PORT` 環境変数を使って PostgreSQL サービスの IP アドレスとポートを指定します。\n`host` と `port` が定義されていない場合、既定のホストは `localhost` で、既定のポートは 5432 です。\n\nスクリプトはテーブルを作成し、そのテーブルにプレースホルダーデータを展開します。\n`postgres` データベースにデータが含まれていることをテストするため、スクリプトでテーブルの内容をコンソール ログに出力します。\n\nこのワークフローを実行すると、「PostgreSQL への接続」ステップに次の出力が表示されます。これにより、PostgreSQL テーブルが正常に作成されてデータが追加されたことを確認できます。\n\n```text\nnull [ { id: 1,\n    firstname: 'Mona the',\n    lastname: 'Octocat',\n    age: 9,\n    address:\n     '88 Colin P Kelly Jr St, San Francisco, CA 94107, United States',\n    email: 'octocat@github.com' } ]\n```"}