docker-compose 中的外部链接如何工作?

docker-compose 中的外部链接如何工作?

在 docker compose 中我们有external_links选项,但它如何工作?

只是link写入 /etc/hosts,但external_links事实并非如此。

请解释一下此选项如何工作,因为码头上没有人谈论它。

答案1

当您创建如下 docker-compose.yml 时:

version: '2'

services:
  sleep-one-hour:
    image: alpine
    command: sleep 3600
    external_links:
      - google.com:216.58.222.110

并且不指定默认网络配置,docker-compose 实际上会根据您运行命令的文件夹名称创建自定义默认网络docker-compose up

[myserver:external-links-test] docker-compose up
Creating network "externallinkstest_default" with the default driver
Creating externallinkstest_sleep-one-hour_1
Attaching to externallinkstest_sleep-one-hour_1

然后创建容器并加入这个自定义网络,并在容器加入网络时设置外部链接。你可以检查最近创建的容器并亲自查看:

[myserver:~] docker inspect 1056bb135bc0
[
    {
        "Id": "1056bb135bc0200dcfff1fa25affd561042e0515641adf435e4b63a16903f93d",
        "Created": "2017-01-26T14:31:57.928385177Z",
        ... other info ...
        "NetworkSettings": {
            ... other info ...
            "Networks": {
                "externallinkstest_default": {
                    "IPAMConfig": null,
                    "Links": [
                        "google.com:216.58.222.110"
                    ],
                    "Aliases": [
                        "1056bb135bc0",
                        "sleep-one-hour"
                    ],
                    "NetworkID": "343121714be4750eebf12997fa73c3aaba0f2cf5faace633ab1ca683a2959632",
                    "EndpointID": "74f1a975236a8ab0f60379408faa04022f1b9e398c7b8a541158c4ca889aff98",
                    "Gateway": "172.20.0.1",
                    "IPAddress": "172.20.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:14:00:02"
                }
            }
        }
    }
]

docker-compose up在纯 docker 命令中实际上翻译成这样的内容:

[myserver:external-links-test] docker network create --attachable --subnet 61.0.0.0/24 externallinkstest_default
13f1b9caad1b997245be0fe48922ff04568c7bcf1e3bdd8846d87f53934ca390
[myserver:external-links-test] docker run -d --name externallinkstest_sleep-one-hour_1 alpine sleep 3600
17b642eb4a3cb562783ae76192589d55cb9174cd2c8a705464f62108ff11372c
[myserver:external-links-test] docker network connect --link google.com:216.58.222.110 externallinkstest_default externallinkstest_sleep-one-hour_1

相关内容