Introduction
This guide shows you workflow examples that configure a service container using the Docker Hub postgres
image. The workflow runs a script to create a PostgreSQL client and populate the client with data. To test that the workflow creates and populates the PostgreSQL client, the script prints the client's data to the console.
Nota: Si tus flujos de trabajo utilizan acciones de contenedor de Docker o contenedores de servicio, entonces debes utilizar un ejecutor de Linux:
- Si estás utilizando ejecutores hospedados en GitHub, debes utilizar el ejecutor
ubuntu-latest
. - Si estás utilizando ejecutores auto-hospedados, debes utilizar una máquina Linux como tu ejecutor, y ésta debe tener Docker instalado.
Prerequisites
Debes familiarizarte con la forma en la que trabajan los contenedores de servicio con GitHub Actions y las diferencias de conexión de red entre los jobs que se están ejecutando directamente en el ejecutor y las que lo hacen en un contenedor. Para obtener más información, consulta la sección "Acerca de los contenedores de servicios".
You may also find it helpful to have a basic understanding of YAML, the syntax for GitHub Actions, and PostgreSQL. For more information, see:
- "Learn GitHub Actions"
- "PostgreSQL tutorial" in the PostgreSQL documentation
Running jobs in containers
La configuración de jobs para su ejecución en un contenedor simplifica las configuraciones de red entre el job y los contenedores de servicio. Los contenedores de Docker en el mismo puente de red definido por el usuario exponen todos los puertos entre ellos, así que no necesitas mapear ninguno de los puertos para contenedores de servicio en el alojamiento de Docker. Puedes acceder al contenedor de servicio desde el contenedor del job utilizando la etiqueta que configuras en el flujo de trabajo.
Puedes copiar este archivo de flujo de trabajo al directorio .github/workflows
de tu repositorio y modificarlo como lo requieras.
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:10.18-jessie
# 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@v2
# 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 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 PostgreSQL client.
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
Este flujo de trabajo configura un job que se ejecuta en el contenedor node:10.18-jessie
y utiiza el ejecutor ubuntu-latest
hospedado en GitHub como el alojamiento de Docker para el contenedor. Para obtener más información acerca del contenedor node:10.18-jessie
, consulta la imagen del nodo en Docker Hub.
El flujo de trabajo configura un contenedor de servicio con la etiqueta postgres
. Todos los servicios se deben ejecutar en un contenedor, entonces cada servicio requiere que especifiques la image
del mismo. Este ejemplo utiliza la imagen del contenedor postgres
, proporciona la cotraseña predeterminada de PostgreSQL, e incluye las opciones de revisión de estado para garantizar que el servicio se está ejecutando. Para obtener más información, consulta la imagen de postgre en 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:10.18-jessie
# 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
El flujo de trabajo realiza los siguientes pasos:
- Verifica el repositorio en el ejecutor
- Instala las dependencias
- Ejecuta un script para crear un cliente
steps:
# Downloads a copy of the code in your repository before running CI tests
- name: Check out repository code
uses: actions/checkout@v2
# 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 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 PostgreSQL client.
env:
# The hostname used to communicate with the PostgreSQL service container
POSTGRES_HOST: postgres
# The default PostgreSQL port
POSTGRES_PORT: 5432
El script client.js busca las variables del ambiente de POSTGRES_HOST
y POSTGRES_PORT
para crear al cliente. El flujo de trabajo configura estas dos variables de ambiente como parte del paso "Conectar a PostgreSQL" para hacerlos disponibles para el script client.js. Para obtener más información acerca del script, consulta "Probar el contenedor de servicio de 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.
Puedes copiar este archivo de flujo de trabajo al directorio .github/workflows
de tu repositorio y modificarlo como lo requieras.
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@v2
# 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 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 PostgreSQL client.
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
El ejemplo utiliza el ejecutor ubuntu-latest
hospedado en GitHub como el hospedaje de Docker.
El flujo de trabajo configura un contenedor de servicio con la etiqueta postgres
. Todos los servicios se deben ejecutar en un contenedor, entonces cada servicio requiere que especifiques la image
del mismo. Este ejemplo utiliza la imagen del contenedor postgres
, proporciona la cotraseña predeterminada de PostgreSQL, e incluye las opciones de revisión de estado para garantizar que el servicio se está ejecutando. Para obtener más información, consulta la imagen de postgre en Docker Hub.
The workflow maps port 5432 on the PostgreSQL service container to the Docker host. For more information about the ports
keyword, see "About service containers."
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
El flujo de trabajo realiza los siguientes pasos:
- Verifica el repositorio en el ejecutor
- Instala las dependencias
- Ejecuta un script para crear un cliente
steps:
# Downloads a copy of the code in your repository before running CI tests
- name: Check out repository code
uses: actions/checkout@v2
# 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 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 PostgreSQL client.
env:
# The hostname used to communicate with the PostgreSQL service container
POSTGRES_HOST: localhost
# The default PostgreSQL port
POSTGRES_PORT: 5432
El script client.js busca las variables del ambiente de POSTGRES_HOST
y POSTGRES_PORT
para crear al cliente. El flujo de trabajo configura estas dos variables de ambiente como parte del paso "Conectar a PostgreSQL" para hacerlos disponibles para el script client.js. Para obtener más información acerca del script, consulta "Probar el contenedor de servicio de PostgreSQL".
El nombre del hospedaje es localhost
o 127.0.0.1
.
Testing the PostgreSQL service container
You can test your workflow using the following script, which creates a PostgreSQL client and adds a new table with some placeholder data. The script then prints the values stored in the PostgreSQL client 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 creates the PostgreSQL client instance, creates a table, adds placeholder data, then retrieves the data.
Agrega a tu repositorio un archivo nuevo llamado client.js con el siguiente 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', 'octocat@github.com']
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 PostgreSQL Client
, which accepts a host
and port
parameter. The script uses the POSTGRES_HOST
and POSTGRES_PORT
environment variables to set the client's 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 PostgreSQL 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 confirming you created the PostgreSQL client 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: 'octocat@github.com' } ]