【问题标题】:Accessing GitLab CI Service from A Container running Inside DinD从运行在 DinD 内部的容器访问 GitLab CI 服务
【发布时间】:2019-04-26 06:31:57
【问题描述】:

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

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

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

我已经用简单的ping 脚本在a public repository 中复制了它

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'

如何访问该服务?

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

【问题讨论】:

  • 你的脚本的第二个命令去服务docker:dind所以高山容器在docker:dind里面并且看不到postgres

标签: docker gitlab gitlab-ci


【解决方案1】:

解决方案是使用--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 的主机添加到嵌套容器中,如上所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 2021-06-07
    • 2022-11-08
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2018-02-02
    • 2019-01-28
    相关资源
    最近更新 更多