Примечание.
GitHubразмещенные в данный момент средства выполнения не поддерживаются в GitHub Enterprise Server.
Введение
В этом руководстве приведены примеры рабочих процессов, которые настраивают контейнер службы с помощью образа Docker Hubredis. Рабочий процесс запускает сценарий для создания клиента Redis и его заполнения данными. Чтобы убедиться в том, что рабочий процесс создает и заполняет клиент Redis, сценарий выводит данные клиента в консоль.
Примечание.
Если в рабочих процессах используются действия контейнеров Docker, контейнеры заданий или контейнеры служб, необходимо использовать средство выполнения Linux:
- При использовании размещенных в GitHub средств выполнения необходимо применять средство выполнения Ubuntu.
- Если вы применяете локальные средства выполнения, необходимо использовать компьютер Linux в качестве средства выполнения, а Docker нужно установить.
Необходимые компоненты
Вы должны знать, как контейнеры служб работают с GitHub Actions. Кроме того, вам должны быть известны сетевые различия между выполнением заданий непосредственно в средстве выполнения или в контейнере. Дополнительные сведения см. в разделе Взаимодействие с контейнерами служб Docker.
Кроме того, вы можете получить общее представление о синтаксисе YAML для GitHub Actions и Redis. Дополнительные сведения см. в разделе:
Выполнение заданий в контейнерах
Настройка заданий для запуска в контейнере упрощает сетевые конфигурации между заданием и контейнерами служб. Контейнеры Docker в одной пользовательской сети моста предоставляют все порты друг другу, поэтому вам не нужно сопоставлять порты контейнера службы с узлом Docker. Вы можете получить доступ к контейнеру службы из контейнера заданий с помощью метки, настроенной в рабочем процессе.
Этот файл рабочего процесса можно скопировать в каталог .github/workflows репозитория и при необходимости изменить его.
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:20-bookworm-slim
# 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@v5
# 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
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:20-bookworm-slim
# 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@v5
# 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:20-bookworm-slim и использует ubuntu-latest средство запуска в качестве узла Docker для контейнера. Дополнительные сведения о контейнере node:20-bookworm-slim см. в статье об образе узла в Docker Hub.
Рабочий процесс настраивает контейнер службы с меткой redis. Все службы должны выполняться в контейнере, поэтому для каждой из них требуется указать image контейнера. В этом примере используется образ контейнера redis и включены параметры проверки работоспособности, чтобы убедиться, что служба запущена. Добавьте тег к имени изображения, чтобы указать версию, например. redis:6 Дополнительные сведения см. в разделе Образ Redis на 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
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
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
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@v5
# 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
steps:
# Downloads a copy of the code in your repository before running CI tests
- name: Check out repository code
uses: actions/checkout@v5
# 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_HOST и REDIS_PORT для создания клиента. Эти две переменные среды задаются на шаге рабочего процесса "Подключение к Redis", после чего становятся доступны скрипту client.js. Дополнительные сведения о скрипте см. в разделе "Тестирование контейнера службы Redis".
Имя узла службы Redis — это метка, настроенная в рабочем процессе; в данном случае — redis. Так как контейнеры Docker в той же пользовательской сети моста открывают все порты по умолчанию, вы можете получить доступ к контейнеру службы через стандартный порт Redis 6379.
Выполнение заданий непосредственно на компьютере средства выполнения тестов
При запуске задания непосредственно на компьютере средства выполнения тестов необходимо сопоставить порты контейнера службы с портами на узле Docker. Вы можете получить доступ к контейнерам служб из узла Docker, используя localhost и номер порта узла Docker.
Этот файл рабочего процесса можно скопировать в каталог .github/workflows репозитория и при необходимости изменить его.
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@v5
# 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
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@v5
# 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
Настройка задания средства выполнения тестов
В примере используется ubuntu-latest метод в качестве узла Docker.
Рабочий процесс настраивает контейнер службы с меткой redis. Все службы должны выполняться в контейнере, поэтому для каждой из них требуется указать image контейнера. В этом примере используется образ контейнера redis и включены параметры проверки работоспособности, чтобы убедиться, что служба запущена. Добавьте тег к имени изображения, чтобы указать версию, например. redis:6 Дополнительные сведения см. в разделе Образ Redis на Docker Hub.
Рабочий процесс сопоставляет порт 6379 в контейнере службы Redis с узлом Docker. Дополнительные сведения о ключевом слове ports см. в разделе Взаимодействие с контейнерами служб Docker.
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
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@v5
# 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
steps:
# Downloads a copy of the code in your repository before running CI tests
- name: Check out repository code
uses: actions/checkout@v5
# 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_HOST и REDIS_PORT для создания клиента. Эти две переменные среды задаются на шаге рабочего процесса "Подключение к Redis", после чего становятся доступны скрипту client.js. Дополнительные сведения о скрипте см. в разделе "Тестирование контейнера службы Redis".
Имя узла — localhost или 127.0.0.1.
Тестирование контейнера службы Redis
Вы можете протестировать рабочий процесс с помощью следующего сценария, который создает клиент Redis и заполняет клиент данными заполнителя. Затем сценарий выводит в терминал значения, хранящиеся в клиенте Redis. Сценарий может использовать любой выбранный язык, но в этом примере используется Node.js и модуль npm redis. Дополнительные сведения см. в модуле npm redis.
Вы можете изменить client.js, чтобы включить все операции Redis, необходимые для вашего рабочего процесса. В этом примере сценарий создает экземпляр клиента Redis, добавляет данные заполнителя, а затем извлекает данные.
Добавьте в репозиторий новый файл client.js с приведенным ниже кодом.
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
}
})();
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
}
})();
Сценарий создает новый клиент Redis с помощью метода createClient, который принимает параметр host и port. Сценарий использует переменные среды REDIS_HOST и REDIS_PORT для настройки IP-адреса порта клиента. Если host и port не определены, по умолчанию используется узел localhost и порт 6379.
Сценарий использует методы set и hset для заполнения базы данных ключами, полями и значениями. Чтобы убедиться, что клиент Redis содержит эти данные, сценарий выводит содержимое базы данных в журнал консоли.
При запуске этого рабочего процесса вы увидите следующие выходные данные на шаге «Подключение к Redis», подтверждающие, что вы создали клиент Redis и добавили данные:
Reply: OK
Reply: 1
Reply: 1
Reply: 1
3 replies:
0: octocat
1: dinotocat
2: robotocat