Observação
No momento, não há suporte para executores hospedados no GitHub no GitHub Enterprise Server. Você pode ver mais informações sobre o suporte futuro planejado no GitHub public roadmap.
Introduction
This guide shows you workflow examples that configure a service container using the Docker Hub postgres
image. The workflow runs a script that connects to the PostgreSQL service, creates a table, and then populates it with data. To test that the workflow creates and populates the PostgreSQL table, the script prints the data from the table to the console.
Observação
Se os fluxos de trabalho usarem ações de contêiner do Docker, contêineres de trabalho ou contêineres de serviço, você precisará usar um executor do Linux:
- Se você estiver usando executores hospedados em GitHub, você deverá usar um executor do Ubuntu.
- Se você estiver usando executores auto-hospedados, você deve usar uma máquina Linux, pois seu executor e o Docker precisam ser instalados.
Prerequisites
Você deve estar familiarizado com como os contêineres de serviço funcionam com GitHub Actions e as diferenças de rede entre trabalhos em execução diretamente no executor ou em um contêiner. Para saber mais, confira Sobre os contêineres de serviço.
You may also find it helpful to have a basic understanding of YAML, the syntax for GitHub Actions, and PostgreSQL. For more information, see:
- Writing workflows
- PostgreSQL tutorial in the PostgreSQL documentation
Running jobs in containers
A configuração de tarefas a serem executadas em um contêiner simplifica as configurações de rede entre o trabalho e os contêineres do serviço. Docker contêineres na mesma rede de ponte definida pelo usuário expõe todas as portas umas para as outras, então você não precisa mapear nenhuma das portas de contêiner de serviço para o host Docker. Você pode acessar o contêiner de serviço do contêiner de trabalho usando a etiqueta que você configurar no fluxo de trabalho.
Você pode copiar esse arquivo de fluxo de trabalho para o diretório .github/workflows
do repositório e modificá-lo conforme necessário.
name: PostgreSQL service 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:20-bookworm-slim # Service containers to run with `container-job` services: # Label used to access the service container postgres: # Docker Hub image image: postgres # Provide the password for postgres env: POSTGRES_PASSWORD: postgres # Set health checks to wait until postgres has started options: >- --health-cmd pg_isready --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 PostgreSQL # Runs a script that creates a PostgreSQL table, populates # the table with data, and then retrieves the data. run: node client.js # Environment variables used by the `client.js` script to create a new PostgreSQL table. env: # The hostname used to communicate with the PostgreSQL service container POSTGRES_HOST: postgres # The default PostgreSQL port POSTGRES_PORT: 5432
name: PostgreSQL service 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:20-bookworm-slim
# Service containers to run with `container-job`
services:
# Label used to access the service container
postgres:
# Docker Hub image
image: postgres
# Provide the password for postgres
env:
POSTGRES_PASSWORD: postgres
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--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 PostgreSQL
# Runs a script that creates a PostgreSQL table, populates
# the table with data, and then retrieves the data.
run: node client.js
# Environment variables used by the `client.js` script to create a new PostgreSQL table.
env:
# The hostname used to communicate with the PostgreSQL service container
POSTGRES_HOST: postgres
# The default PostgreSQL port
POSTGRES_PORT: 5432
Configuring the runner job for jobs in containers
Este fluxo de trabalho configura uma tarefa que é executada no contêiner node:20-bookworm-slim
e usa o executor do ubuntu-latest
como host do Docker para o contêiner. Para obter mais informações sobre o contêiner node:20-bookworm-slim
, confira a imagem do nó no Docker Hub.
O fluxo de trabalho configura um contêiner de serviço com o rótulo postgres
. Todos os serviços precisam ser executados em um contêiner, ou seja, cada serviço exige que você especifique o contêiner image
. Este exemplo usa a imagem de contêiner postgres
, fornece a senha padrão do PostgreSQL e inclui opções de verificação de integridade para verificar se o serviço está em execução. Para obter mais informações, confira a imagem do Postgres no Docker Hub.
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:20-bookworm-slim # Service containers to run with `container-job` services: # Label used to access the service container postgres: # Docker Hub image image: postgres # Provide the password for postgres env: POSTGRES_PASSWORD: postgres # Set health checks to wait until postgres has started options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
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:20-bookworm-slim
# Service containers to run with `container-job`
services:
# Label used to access the service container
postgres:
# Docker Hub image
image: postgres
# Provide the password for postgres
env:
POSTGRES_PASSWORD: postgres
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
Configuring the steps for jobs in containers
O fluxo de trabalho executa as seguintes etapas:
- Verifica o repositório no executor
- Instala dependências
- Executa um script para criar um cliente
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 PostgreSQL # Runs a script that creates a PostgreSQL table, populates # the table with data, and then retrieves the data. run: node client.js # Environment variable used by the `client.js` script to create # a new PostgreSQL client. env: # The hostname used to communicate with the PostgreSQL service container POSTGRES_HOST: postgres # The default PostgreSQL port POSTGRES_PORT: 5432
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 PostgreSQL
# Runs a script that creates a PostgreSQL table, populates
# the table with data, and then retrieves the data.
run: node client.js
# Environment variable used by the `client.js` script to create
# a new PostgreSQL client.
env:
# The hostname used to communicate with the PostgreSQL service container
POSTGRES_HOST: postgres
# The default PostgreSQL port
POSTGRES_PORT: 5432
O script client.js procura as variáveis de ambiente POSTGRES_HOST
e POSTGRES_PORT
para criar o cliente. O fluxo de trabalho define essas duas variáveis de ambiente como parte da etapa "Conectar-se ao PostgreSQL" para disponibilizá-las ao script client.js. Para obter mais informações sobre o script, confira Como testar o contêiner do serviço do PostgreSQL.
The hostname of the PostgreSQL service is the label you configured in your workflow, in this case, postgres
. Because Docker containers on the same user-defined bridge network open all ports by default, you'll be able to access the service container on the default PostgreSQL port 5432.
Running jobs directly on the runner machine
When you run a job directly on the runner machine, you'll need to map the ports on the service container to ports on the Docker host. You can access service containers from the Docker host using localhost
and the Docker host port number.
Você pode copiar esse arquivo de fluxo de trabalho para o diretório .github/workflows
do repositório e modificá-lo conforme necessário.
name: PostgreSQL Service 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 postgres: # Docker Hub image image: postgres # Provide the password for postgres env: POSTGRES_PASSWORD: postgres # Set health checks to wait until postgres has started options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: # Maps tcp port 5432 on service container to the host - 5432:5432 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 PostgreSQL # Runs a script that creates a PostgreSQL table, populates # the table with data, and then retrieves the data run: node client.js # Environment variables used by the `client.js` script to create # a new PostgreSQL table. env: # The hostname used to communicate with the PostgreSQL service container POSTGRES_HOST: localhost # The default PostgreSQL port POSTGRES_PORT: 5432
name: PostgreSQL Service 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
postgres:
# Docker Hub image
image: postgres
# Provide the password for postgres
env:
POSTGRES_PASSWORD: postgres
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps tcp port 5432 on service container to the host
- 5432:5432
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 PostgreSQL
# Runs a script that creates a PostgreSQL table, populates
# the table with data, and then retrieves the data
run: node client.js
# Environment variables used by the `client.js` script to create
# a new PostgreSQL table.
env:
# The hostname used to communicate with the PostgreSQL service container
POSTGRES_HOST: localhost
# The default PostgreSQL port
POSTGRES_PORT: 5432
Configuring the runner job for jobs directly on the runner machine
O exemplo usa o executor hospedado no ubuntu-latest
como o host do Docker.
O fluxo de trabalho configura um contêiner de serviço com o rótulo postgres
. Todos os serviços precisam ser executados em um contêiner, ou seja, cada serviço exige que você especifique o contêiner image
. Este exemplo usa a imagem de contêiner postgres
, fornece a senha padrão do PostgreSQL e inclui opções de verificação de integridade para verificar se o serviço está em execução. Para obter mais informações, confira a imagem do Postgres no Docker Hub.
The workflow maps port 5432 on the PostgreSQL service container to the Docker host. For more information about the ports
keyword, see Sobre os contêineres de serviço.
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 postgres: # Docker Hub image image: postgres # Provide the password for postgres env: POSTGRES_PASSWORD: postgres # Set health checks to wait until postgres has started options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: # Maps tcp port 5432 on service container to the host - 5432:5432
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
postgres:
# Docker Hub image
image: postgres
# Provide the password for postgres
env:
POSTGRES_PASSWORD: postgres
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps tcp port 5432 on service container to the host
- 5432:5432
Configuring the steps for jobs directly on the runner machine
O fluxo de trabalho executa as seguintes etapas:
- Verifica o repositório no executor
- Instala dependências
- Executa um script para criar um cliente
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 PostgreSQL # Runs a script that creates a PostgreSQL table, populates # the table with data, and then retrieves the data run: node client.js # Environment variables used by the `client.js` script to create # a new PostgreSQL table. env: # The hostname used to communicate with the PostgreSQL service container POSTGRES_HOST: localhost # The default PostgreSQL port POSTGRES_PORT: 5432
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 PostgreSQL
# Runs a script that creates a PostgreSQL table, populates
# the table with data, and then retrieves the data
run: node client.js
# Environment variables used by the `client.js` script to create
# a new PostgreSQL table.
env:
# The hostname used to communicate with the PostgreSQL service container
POSTGRES_HOST: localhost
# The default PostgreSQL port
POSTGRES_PORT: 5432
O script client.js procura as variáveis de ambiente POSTGRES_HOST
e POSTGRES_PORT
para criar o cliente. O fluxo de trabalho define essas duas variáveis de ambiente como parte da etapa "Conectar-se ao PostgreSQL" para disponibilizá-las ao script client.js. Para obter mais informações sobre o script, confira Como testar o contêiner do serviço do PostgreSQL.
O nome do host é localhost
ou 127.0.0.1
.
Testing the PostgreSQL service container
You can test your workflow using the following script, which connects to the PostgreSQL service and adds a new table with some placeholder data. The script then prints the values stored in the PostgreSQL table to the terminal. Your script can use any language you'd like, but this example uses Node.js and the pg
npm module. For more information, see the npm pg module.
You can modify client.js to include any PostgreSQL operations needed by your workflow. In this example, the script connects to the PostgreSQL service, adds a table to the postgres
database, inserts some placeholder data, and then retrieves the data.
Adicione um novo arquivo chamado client.js ao seu repositório com o seguinte código.
const { Client } = require('pg'); const pgclient = new Client({ host: process.env.POSTGRES_HOST, port: process.env.POSTGRES_PORT, user: 'postgres', password: 'postgres', database: 'postgres' }); pgclient.connect(); const 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))' const text = 'INSERT INTO student(firstname, lastname, age, address, email) VALUES($1, $2, $3, $4, $5) RETURNING *' const values = ['Mona the', 'Octocat', 9, '88 Colin P Kelly Jr St, San Francisco, CA 94107, United States', '[email protected]'] pgclient.query(table, (err, res) => { if (err) throw err }); pgclient.query(text, values, (err, res) => { if (err) throw err }); pgclient.query('SELECT * FROM student', (err, res) => { if (err) throw err console.log(err, res.rows) // Print the data in student table pgclient.end() });
const { Client } = require('pg');
const pgclient = new Client({
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
user: 'postgres',
password: 'postgres',
database: 'postgres'
});
pgclient.connect();
const 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))'
const text = 'INSERT INTO student(firstname, lastname, age, address, email) VALUES($1, $2, $3, $4, $5) RETURNING *'
const values = ['Mona the', 'Octocat', 9, '88 Colin P Kelly Jr St, San Francisco, CA 94107, United States', '[email protected]']
pgclient.query(table, (err, res) => {
if (err) throw err
});
pgclient.query(text, values, (err, res) => {
if (err) throw err
});
pgclient.query('SELECT * FROM student', (err, res) => {
if (err) throw err
console.log(err, res.rows) // Print the data in student table
pgclient.end()
});
The script creates a new connection to the PostgreSQL service, and uses the POSTGRES_HOST
and POSTGRES_PORT
environment variables to specify the PostgreSQL service IP address and port. If host
and port
are not defined, the default host is localhost
and the default port is 5432.
The script creates a table and populates it with placeholder data. To test that the postgres
database contains the data, the script prints the contents of the table to the console log.
When you run this workflow, you should see the following output in the "Connect to PostgreSQL" step, which confirms that you successfully created the PostgreSQL table and added data:
null [ { id: 1,
firstname: 'Mona the',
lastname: 'Octocat',
age: 9,
address:
'88 Colin P Kelly Jr St, San Francisco, CA 94107, United States',
email: '[email protected]' } ]