一项服务如何使用 docker 组合、link 主机名和端口解析另一项服务的地址?

How does one service resolve the address of another service using docker compose, link hostname, and ports?

我看了几个围绕同一个问题的SO问题,但是由于积分不足,我无法对现有问题发表评论。因此,我必须提出关于 docker-compose 和链接的我自己的问题线程。

我的印象是,在 docker-compose 文件中包含以下内容会将 'db' 添加到我容器的主机文件中

web:
  links:
    - db

我在想我的网络代码可以建立数据库连接,类似于

db := sql.Open("postgres", "user=foo dbname=baz host=db")

其中主机名 db 存在于我的 Web 容器的 /etc/hostfile 中,因此解析为到达数据库容器的某个地址。

我的 Web 应用程序没有解析到我的数据库所在的地址 运行,而是解析到一个地址 (172.19.0.3),我不知道它来自哪里或如何修复。

docker exec $WEB_CONTAINER_ID cat /etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.19.0.2  6f52f9e78f00

我期待看到 db 的条目。此外:

docker exec $WEB_CONTAINER_ID nslookup db
Name:      db
Address 1: 172.19.0.3 apiserver_postgres_1.apiserver_default

我误会了什么?如何启用我的网络代码来解析我的数据库地址?

这不再是您的经典 docker 1.8 或更低版本“link”,尤其是当您使用 docker-compose.yml 文件的版本 2 时。

issue 3002所述:

version:"2" creates a bridge network by default for your project. If you run docker network ls you'll see a new bridged network where your project containers will be created. (which makes totally sense)

Docker itself has removed these variables from links on any network except for the old bridge network.

现在有一个embedded DNS