docker - 从 DinD 内部运行的容器访问 GitLab CI 服务

标签 docker gitlab gitlab-ci

我正在尝试在 GitLab CI 中运行持续集成,包括:

  • 构建 docker 镜像
  • 运行测试
  • 将 docker 镜像推送到注册表

  • 那些在一份工作中运行。我可以毫无问题地做到这一点,直到出现一些需要与数据库通信的测试。我的容器无法与定义的 Postgres 服务进行通信。

    我在 a public repository 中复制了它与简单 ping脚本
    image: docker:stable
    
    services:
      - docker:dind
      - postgres:latest
    
    job1:
      script:
        - ping postgres -c 5
        - docker run --rm --network="host" alpine:latest sh -c "ping postgres -c 5"
    

    第一个脚本可以正常运行,但第二个脚本失败并出现错误
    ping: bad address 'postgres'
    

    如何访问该服务?

    或者我应该在不同的工作中运行测试?

    最佳答案

    解决方法是使用--add-host=postgres:$POSTGRES_IP传递作业容器中存在的 IP 地址。
    要找出链接到外部容器的 postgres ip,您可以使用例如 getent hosts postgres | awk '{ print $1 }'所以 yml 看起来像

    image: docker:stable
    
    services:
      - docker:dind
      - postgres:latest
    
    job1:
      script:
        - ping postgres -c 5
        - docker run --rm --add-host=postgres:$(getent hosts postgres  | awk '{ print $1 }') alpine:latest sh -c "ping postgres -c 5"
    

    要理解为什么其他更常见的连接容器的方法在这种情况下不起作用,我们必须记住我们正在尝试将嵌套容器与链接到其“父”的服务链接起来。像这样的东西:
    gitlab ci runner --> docker       -> my-container (alpine)
                      -> docker:dind
                      -> postgres
    
    所以我们试图将一个容器与其“叔叔”连接起来。或者连接嵌套容器
    正如@tbo 所指出的,使用 --network host不管用。这可能是因为 gitlab ci 使用了 --link (如 here 所述)连接容器而不是较新的 --network .方式--link作品使服务容器连接到作业容器,但不相互连接。因此,使用主机网络不会使嵌套容器继承 postgres 主机名。
    也可以认为使用 --link postgres:postgres会起作用,但它也不会,因为在这种环境中 postgres 只是一个带有外部容器 ip 的主机名。此处没有容器可与嵌套容器链接
    因此,我们所能做的就是使用 --add-host 手动将具有正确 ip 的主机添加到嵌套容器中。如上所述。

    关于docker - 从 DinD 内部运行的容器访问 GitLab CI 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55861985/

    相关文章:

    yaml - GitLab 中的 Concat 变量名

    git - 如何在 Gitlab CI 中获取 Gitlab merge 请求描述?

    python - 在docker-py中使用管道

    Docker 匿名卷

    bash - 在Java应用程序中从Docker收集输出

    version-control - 如何在 Firebase 上实现版本控制?

    docker - 使用 Ansible 获取 Docker 的 IP 地址

    ssh - Gitlab:无法在家中进行 SSH(Windows)

    reactjs - Gitlab 页面和 React Router

    linux - 部署Azure Function的gitlab代码-如何控制版本号