docker-compose 如何为 link ips 创建别名

How does docker-compose create aliases for link ips

当 运行 docker-compose 时,所有容器都有网络别名到网络中其他容器 运行 的 ip。 这些别名是如何创建的?

我需要在 Kubernetes 集群内的 nginx 容器中重新创建一个别名,因为 nginx conf 不允许环境变量,我从那里反向代理请求到另一个容器。 我通常会编辑 /etc/hosts 文件,但由于 docker-compose 没有,我想知道别名是如何创建的,以及我是否可以在我的 kubernetes 集群中以同样的方式进行操作。

documentation

中所写

Containers for the linked service are reachable at a hostname identical to the alias, or the service name if no alias was specified

这意味着如果您有这样的 docker-compose 文件:

version: '3'
services:
  nginx:
     links:
       - app1
     ...
  app1:
    ...

然后nginx可以通过app1访问另一个容器。

在kubernetes集群中,默认部署了一个DNS服务器服务。

kubectl get svc 应显示 DNS 服务 IP 地址。

您也可以在容器 /etc/resolv.conf 文件中找到 DNS 服务器 IP 地址。

有关详细信息,请参阅 here

您可以使用 HostAliases 在容器的 /etc/hosts 文件中指定其他条目。参见 here

剪断:

apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "foo.local"
    - "bar.local"
  - ip: "10.1.2.3"
    hostnames:
    - "foo.remote"
    - "bar.remote"