less than 1 minute read

GitHub Actions Workflow를 사용해 테스트를 돌린다. 테스트할 때, database가 필요해서 사용하는 방법을 알아봤다.

서비스 컨테이너(service container)를 사용하면 도커(docker) 컨테이너를 손쉽게 띄울 수 있다. 아래는 서비스 컨테이너로 postgresql을 실행하는 workflow다. ’Creating PostgreSQL service containers - GitHub Docs - docs.github.com’ 글을 참고했다.

jobs:
  test:
    services:
      db:
        image: postgres:12
        ports: ['5432:5432']
        env:
          POSTGRES_PASSWORD: postgres
          options: >-
            --health-cmd pg_isready
            --health-interval 10s
            --health-timeout 5s
            --health-retries 5

애플리케이션에 database 정보를 전달해야 한다. 전달 방법으로 환경 변수를 선택했다.

env:
  DATABASE_NAME: mydb
  DATABASE_USERNAME: postgres
  DATABASE_HOSTNAME: localhost
  DATABASE_PASSWORD: postgres
  DATABASE_PORT: 5432

localhost 가 호스트 이름이다.

database 관련 설정을 모두 환경 변수로 정의했다. 애플리케이션에서는 이 환경 변수를 읽어서 애플리케이션에서 사용할 database 저장소 설정을 하면 된다.

config :awesome_app, AwesomeApp.Repo,
  database: System.get_env("DATABASE_NAME"),
  username: System.get_env("DATABASE_USERNAME"),
  password: System.get_env("DATABASE_PASSWORD"),
  hostname: System.get_env("DATABASE_HOSTNAME"),
  port: System.get_env("DATABASE_PORT", "5432")

서비스 컨테이너 최고다. workflow에 필요한 도커 컨테이너를 손쉽게 실행할 수 있다.