首页 > 解决方案 > Github Actions 数据库服务容器无法访问

问题描述

我有以下 Github Actions 管道:

name: Elixir CI

on:
  push:
    branches:
      - '*'

  pull_request:
    branches:
        - '*'

jobs:
  build:
    name: Build and test
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: password
          POSTGRES_PORT: 5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432
    steps:
    - uses: actions/checkout@v2
    - name: Docker Setup Buildx
      uses: docker/setup-buildx-action@v1.6.0
      with:
        install: true
    - name: building image
      env:
        DATABASE_HOST: postgres
        DATABASE_PORT: 5432
      run: |
        docker build --build-arg DATABASE_HOST=$DATABASE_HOST -t backend:test -f Dockerfile.ci .

我有一个 Elixir 应用程序的构建步骤:dockerfile 是多阶段的,第一阶段运行测试并构建生产应用程序,第二阶段复制应用程序文件夹/tar。

DATABASE_HOST是我的 Elixir 应用程序寻找连接到测试环境的变量。

我需要针对 Postgres 运行测试,所以我用它生成了一个容器服务。我已经在容器中和容器外执行了构建,但总是出现以下错误:


...

#19 195.9 14:10:58.624 [error] GenServer #PID<0.9316.0> terminating
#19 195.9 ** (DBConnection.ConnectionError) tcp connect (postgres:5432): non-existing domain - :nxdomain
#19 195.9     (db_connection 2.4.1) lib/db_connection/connection.ex:100: DBConnection.Connection.connect/2
#19 195.9     (connection 1.1.0) lib/connection.ex:622: Connection.enter_connect/5
#19 195.9     (stdlib 3.14.2.2) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
#19 195.9 Last message: nil
...

所以显然postgres:5432无法到达,我错过了什么吗?

标签: dockergithubelixirgithub-actions

解决方案


问题出在DATABASE_HOST: postgres我想。

服务容器将5432端口导出到主机,因此对于 docker build,它应该使用如下host's ip address访问postgres service

- name: building image
  env:
    DATABASE_PORT: 5432
  run: |
    DATABASE_HOST=$(ifconfig -a eth0|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:")
    docker build --build-arg DATABASE_HOST=$DATABASE_HOST -t backend:test -f Dockerfile.ci .

上面会先ifconfig用来获取虚拟机的ip(docker host's ip),然后传给docker build让build容器访问postgres。


推荐阅读