{"meta":{"title":"PostgreSQL 서비스 컨테이너 만들기","intro":"워크플로에서 사용할 PostgreSQL 서비스 컨테이너를 만들 수 있습니다. 이 가이드에서는 컨테이너 또는 실행기 컴퓨터에서 직접 실행되는 작업에 대한 PostgreSQL 서비스를 만드는 예제를 보여 줍니다.","product":"GitHub Actions","breadcrumbs":[{"href":"/ko/actions","title":"GitHub Actions"},{"href":"/ko/actions/tutorials","title":"자습서"},{"href":"/ko/actions/tutorials/use-containerized-services","title":"컨테이너화된 서비스 사용"},{"href":"/ko/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서비스 컨테이너가 GitHub Actions에서 작동하는 방식과 실행기 또는 컨테이너에서 직접 실행 중인 작업 간의 네트워킹 차이점에 대해 잘 알고 있어야 합니다. 자세한 내용은 [Docker 서비스 컨테이너와 통신](/ko/actions/using-containerized-services/about-service-containers)을(를) 참조하세요.\n\nYAML, GitHub Actions의 구문 및 PostgreSQL에 대한 기본적인 이해가 도움이 될 수도 있습니다. 자세한 내용은 다음을 참조하세요.\n\n* [워크플로 작성](/ko/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@v6\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워크플로는 `postgres` 레이블을 사용하여 서비스 컨테이너를 구성합니다. 모든 서비스는 컨테이너에서 실행되어야 하므로 각 서비스는 컨테이너 `image`를 지정해야 합니다. 이 예제에서는 `postgres` 컨테이너 이미지를 사용하고, 기본 PostgreSQL 암호를 제공하며, 서비스가 실행 중인지 확인하기 위한 상태 검사 옵션을 포함합니다. 자세한 내용은 Docker Hub의 [postgres 이미지](https://hub.docker.com/_/postgres)를 참조하세요.\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@v6\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*client.js* 스크립트는 클라이언트를 만들 `POSTGRES_HOST` 환경 변수 및 `POSTGRES_PORT` 환경 변수를 찾습니다. 워크플로는 두 환경 변수를 \"PostgreSQL에 커넥트\" 단계의 일부로 설정하여 *client.js* 스크립트에 사용할 수 있도록 합니다. 스크립트에 대한 자세한 내용은 [PostgreSQL 서비스 컨테이너 테스트](#testing-the-postgresql-service-container)를 참조하세요.\n\nPostgreSQL 서비스의 호스트 이름은 워크플로에서 구성한 레이블(이 경우 `postgres`)입니다. 동일한 사용자 정의 브리지 네트워크의 Docker 컨테이너는 기본적으로 모든 포트를 열기 때문에 기본 PostgreSQL 포트 5432의 서비스 컨테이너에 액세스할 수 있습니다.\n\n## 러너 머신에서 직접 작업 실행\n\n실행기 컴퓨터에서 직접 작업을 실행하는 경우 서비스 컨테이너의 포트를 Docker 호스트의 포트에 매핑해야 합니다.\n`localhost` 및 Docker 호스트 포트 번호를 사용하여 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@v6\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\n워크플로는 `postgres` 레이블을 사용하여 서비스 컨테이너를 구성합니다. 모든 서비스는 컨테이너에서 실행되어야 하므로 각 서비스는 컨테이너 `image`를 지정해야 합니다. 이 예제에서는 `postgres` 컨테이너 이미지를 사용하고, 기본 PostgreSQL 암호를 제공하며, 서비스가 실행 중인지 확인하기 위한 상태 검사 옵션을 포함합니다. 자세한 내용은 Docker Hub의 [postgres 이미지](https://hub.docker.com/_/postgres)를 참조하세요.\n\n워크플로는 PostgreSQL 서비스 컨테이너의 포트 5432를 Docker 호스트에 매핑합니다.\n`ports` 키워드에 대한 자세한 내용은 [Docker 서비스 컨테이너와 통신](/ko/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@v6\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*client.js* 스크립트는 클라이언트를 만들 `POSTGRES_HOST` 환경 변수 및 `POSTGRES_PORT` 환경 변수를 찾습니다. 워크플로는 두 환경 변수를 \"PostgreSQL에 커넥트\" 단계의 일부로 설정하여 *client.js* 스크립트에 사용할 수 있도록 합니다. 스크립트에 대한 자세한 내용은 [PostgreSQL 서비스 컨테이너 테스트](#testing-the-postgresql-service-container)를 참조하세요.\n\n호스트 이름은 `localhost` 또는 `127.0.0.1`입니다.\n\n## PostgreSQL 서비스 컨테이너 테스트\n\nPostgreSQL 서비스에 연결하고 일부 자리 표시자 데이터가 있는 새 테이블을 추가하는 다음 스크립트를 사용하여 워크플로를 테스트할 수 있습니다. 그런 다음, 스크립트는 PostgreSQL 테이블에 저장된 값을 터미널에 출력합니다. 스크립트는 원하는 언어를 사용할 수 있지만 이 예제에서는 Node.js 및 `pg` npm 모듈을 사용합니다. 자세한 내용은 [npm pg 모듈](https://www.npmjs.com/package/pg)을 참조하세요.\n\n워크플로에 필요한 PostgreSQL 작업을 포함하도록 \\_client.js\\_를 수정할 수 있습니다. 이 예제에서 스크립트는 PostgreSQL 서비스에 연결하고, `postgres` 데이터베이스에 테이블을 추가하고, 일부 자리 표시자 데이터를 삽입한 다음, 데이터를 검색합니다.\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```"}