我正在尝试在 GitLab CI 中运行持续集成,包括:
那些在一份工作中运行。我可以毫无问题地做到这一点,直到出现一些需要与数据库通信的测试。我的容器无法与定义的 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/