has*_*ash 6 gitlab docker gitlab-ci
我正在尝试在 GitLab CI 中运行持续集成,其中包括:
这些都在一项工作中运行。我可以毫无问题地做到这一点,直到出现一些需要与数据库通信的测试。我的容器无法与定义的 Postgres 服务通信。
我已经用简单的脚本在公共存储库中重现了它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"
Run Code Online (Sandbox Code Playgroud)
第一个脚本可以正常运行,但第二个脚本失败并出现错误
ping: bad address 'postgres'
Run Code Online (Sandbox Code Playgroud)
我如何访问该服务?
或者我应该在不同的工作中运行测试?
解决方案是使用--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"
Run Code Online (Sandbox Code Playgroud)
要理解为什么其他更常见的连接容器的方法在这种情况下不起作用,我们必须记住我们正在尝试将嵌套容器与链接到其“父级”的服务链接起来。像这样的东西:
gitlab ci runner --> docker -> my-container (alpine)
-> docker:dind
-> postgres
Run Code Online (Sandbox Code Playgroud)
所以我们试图将一个容器与其“叔叔”连接起来。或者连接嵌套容器
正如@tbo 所指出的,使用--network host将不起作用。这可能是因为 gitlab ci 使用--link (如此处所述)来连接容器而不是较新的容器--network。这种工作方式--link使得服务容器连接到作业容器,但彼此之间不连接。因此,使用主机网络不会使嵌套容器继承 postgres 主机名。
人们也可能认为 using--link postgres:postgres可以工作,但它也不会工作,因为在这种环境中 postgres 只是一个带有外部容器 IP 的主机名。这里没有容器可以与嵌套容器链接
因此,我们所能做的就是按照上面的说明手动将具有正确 IP 的主机添加到嵌套容器中--add-host。
| 归档时间: |
|
| 查看次数: |
1224 次 |
| 最近记录: |