将容器主机名动态解析为 IP

Dynamically resolving container hostname to an IP

我在 docker-compose.yml 中有多个服务需要相互通信。这不是问题,因为作曲家在内部负责所有网络。但是,其中一项服务需要白名单才能与其 API 通信。遗憾的是,此白名单仅限于 IPv4 地址 - 它不解析主机名。

我想避免必须定义自己的自定义网络并为容器分配静态 IP 地址,从而保持灵活性。我上下搜索过,但没有找到在运行时甚至构建阶段解析服务名称的方法。

我已尝试安装 DNS 工具并使用 dig,但无法确定 IP 地址。这可能与我不了解 Docker 如何处理网络层有关。

所以我的问题是:

一个月前我遇到过类似的挑战,有可能获得你想要的东西(即使我在 Kubernetes 上工作而不是 docker-compose)。

Docker 提供内部 DNS 解析系统,如本 中所述。 如果您使用 dig 进行一些破解,您会发现容器使用与您的主机不同的 DNS IP。

特别是,launching the Wordpress example 形成 docker-compose 文档,您可以通过以下方式查看它:

mkdir /tmp/test && cd /tmp/test
# create a docker-compose.yaml file and past the example from the link above
docker-compose up -d
# it should be test_default, check it out with `docker network ls`
docker run --rm -it --network test_default ubuntu /bin/bash

然后,在容器内输入:

apt-get update && apt-get install -y dnsutils
dig wordpress

你应该得到类似这样的东西:

root@91e47b426ed3:/# dig wordpress

; <<>> DiG 9.11.3-1ubuntu1.3-Ubuntu <<>> wordpress
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 17239
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;wordpress.                     IN      A

;; ANSWER SECTION:
wordpress.              600     IN      A       172.18.0.3

;; Query time: 0 msec
;; SERVER: 127.0.0.11#53(127.0.0.11)
;; WHEN: Sun Feb 17 19:39:24 UTC 2019
;; MSG SIZE  rcvd: 52

在这里,您看到字段 SERVER 显示 127.0.0.11#53,在我的例子中,这是内部 Docker DNS 系统。您可以检查该地址是否是报告的地址(在我的例子中是 172.18.0.3)安装 curl 并在端口 80.

到达它

考虑到这一点,您可以创建一个脚本或程序来定期执行地址解析,获取该服务的 DNS returns 地址列表并相应地更新您的白名单。

How can I resolve a containers service name either at runtime or during the build phase?

以Java为例,您可以使用InetAddress class that given an URL it gives back a list of IP4 and IP6 addresses (you can filter them using InetAddressValidator from the Apache Common library). You can see more here (that's how I solved the problem). In Linux, there is a specific syscall, getaddrinfo,获取给定URL的IP列表。

When building with docker-compose, does it assign static addresses to the container or is there a possibility of the containers IP changing after a reboot?

关于第二个问题,docker-compose使用与docker build相同的逻辑,所以它不会分配静态IP地址或类似的。最重要的是,如果容器崩溃并重新启动,则其 IP 可能会发生变化。