Skip to main content

Redis 서비스 컨테이너 만들기

서비스 컨테이너를 사용하여 워크플로에서 Redis 클라이언트를 만들 수 있습니다. 이 가이드에서는 컨테이너 또는 실행기 컴퓨터에서 직접 실행되는 작업에 대한 Redis 서비스를 만드는 예제를 보여 줍니다.

소개

이 가이드에서는 Docker Hub redis 이미지를 사용하여 서비스 컨테이너를 구성하는 워크플로 예제를 보여 줍니다. 워크플로는 스크립트를 실행하여 Redis 클라이언트를 만들고 클라이언트를 데이터로 채웁니다. 워크플로가 Redis 클라이언트를 만들고 채우는지 테스트하기 위해 스크립트는 클라이언트의 데이터를 콘솔에 출력합니다.

참고: 워크플로에서 Docker 컨테이너 작업, 작업 컨테이너 또는 서비스 컨테이너를 사용하는 경우 Linux 실행기를 사용해야 합니다.

  • GitHub에서 호스트되는 실행기를 사용하는 경우 Ubuntu 실행기를 사용해야 합니다.
  • 자체 호스팅 실행기를 사용하는 경우 실행기로 Linux 컴퓨터를 사용해야 하며 Docker를 설치해야 합니다.

필수 조건

서비스 컨테이너가 GitHub Actions에서 작동하는 방식과 실행기 또는 컨테이너에서 직접 실행 중인 작업 간의 네트워킹 차이점에 대해 잘 알고 있어야 합니다. 자세한 내용은 "서비스 컨테이너 정보"을 참조하세요.

YAML, GitHub Actions의 구문 및 Redis에 대한 기본적인 이해가 도움이 될 수도 있습니다. 자세한 내용은 다음을 참조하세요.

컨테이너에서 작업 실행

컨테이너에서 실행되도록 작업을 구성하면 작업과 서비스 컨테이너 간의 네트워킹 구성이 간소화됩니다. 동일한 사용자 정의 브리지 네트워크의 Docker 컨테이너는 모든 포트를 서로 노출하므로 서비스 컨테이너 포트를 Docker 호스트에 매핑할 필요가 없습니다. 워크플로에서 구성하는 레이블을 사용하여 작업 컨테이너에서 서비스 컨테이너에 액세스할 수 있습니다.

이 워크플로 파일을 리포지토리의 .github/workflows 디렉터리에 복사하고 필요에 따라 수정할 수 있습니다.

YAML
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:10.18-jessie

    # 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@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 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:10.18-jessie 컨테이너에서 실행되는 작업을 구성하고 ubuntu-latest GitHub 호스팅 실행기를 컨테이너의 Docker 호스트로 사용합니다. node:10.18-jessie 컨테이너에 대한 자세한 내용은 Docker Hub의 노드 이미지를 참조하세요.

워크플로는 redis 레이블을 사용하여 서비스 컨테이너를 구성합니다. 모든 서비스는 컨테이너에서 실행되어야 하므로 각 서비스는 컨테이너 image를 지정해야 합니다. 이 예제에서는 redis 컨테이너 이미지를 사용하며 서비스가 실행 중인지 확인하기 위한 상태 검사 옵션을 포함합니다. 이미지 이름에 태그를 추가하여 버전을 지정합니다(예: redis:6). 자세한 내용은 Docker Hub Redis 이미지를 참조하세요.

YAML
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
      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

컨테이너 작업 단계 구성

워크플로는 다음 단계를 수행합니다.

  1. 실행기에서 리포지토리 체크 아웃
  2. 종속성 설치
  3. 스크립트를 실행하여 클라이언트 만들기
YAML
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 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 호스트의 포트에 매핑해야 합니다. localhost 및 Docker 호스트 포트 번호를 사용하여 Docker 호스트에서 서비스 컨테이너에 액세스할 수 있습니다.

이 워크플로 파일을 리포지토리의 .github/workflows 디렉터리에 복사하고 필요에 따라 수정할 수 있습니다.

YAML
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@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 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 GitHub 호스팅 실행기를 Docker 호스트로 사용합니다.

워크플로는 redis 레이블을 사용하여 서비스 컨테이너를 구성합니다. 모든 서비스는 컨테이너에서 실행되어야 하므로 각 서비스는 컨테이너 image를 지정해야 합니다. 이 예제에서는 redis 컨테이너 이미지를 사용하며 서비스가 실행 중인지 확인하기 위한 상태 검사 옵션을 포함합니다. 이미지 이름에 태그를 추가하여 버전을 지정합니다(예: redis:6). 자세한 내용은 Docker Hub Redis 이미지를 참조하세요.

워크플로는 Redis 서비스 컨테이너의 포트 6379를 Docker 호스트에 매핑합니다. ports 키워드에 대한 자세한 내용은 "서비스 컨테이너 정보"을(를) 참조하세요.

YAML
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

실행기 작업 단계 구성

워크플로는 다음 단계를 수행합니다.

  1. 실행기에서 리포지토리 체크 아웃
  2. 종속성 설치
  3. 스크립트를 실행하여 클라이언트 만들기
YAML
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 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 및 redis npm 모듈을 사용합니다. 자세한 내용은 npm redis 모듈을 참조하세요.

워크플로에 필요한 Redis 작업을 포함하도록 _client.js_를 수정할 수 있습니다. 이 예제에서 스크립트는 Redis 클라이언트 인스턴스를 만들고 자리 표시자 데이터를 추가한 다음 데이터를 검색합니다.

다음 코드를 사용하여 _client.js_라는 새 파일을 리포지토리에 추가합니다.

JavaScript
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
  }
})();

스크립트는 createClient 메서드를 사용하여 새 Redis 클라이언트를 만듭니다. 이 메서드는 hostport 매개 변수를 허용합니다. 스크립트는 REDIS_HOSTREDIS_PORT 환경 변수를 사용하여 클라이언트의 IP 주소 및 포트를 설정합니다. hostport가 정의되지 않은 경우 기본 호스트는 localhost이고 기본 포트는 6379입니다.

스크립트는 sethset 메서드를 사용하여 일부 키, 필드 및 값으로 데이터베이스를 채웁다. Redis 클라이언트에 데이터가 포함되어 있는지 확인하기 위해 스크립트는 테이블의 내용을 콘솔 로그에 출력합니다.

이 워크플로를 실행할 때 Redis 클라이언트를 만들고 데이터를 추가했는지 확인하는 “Redis에 연결” 단계에서 다음 출력이 표시됩니다.

Reply: OK
Reply: 1
Reply: 1
Reply: 1
3 replies:
    0: octocat
    1: dinotocat
    2: robotocat