互联网技术 / 互联网资讯 · 2024年3月14日

Docker教程:修改Docker容器中的/etc/hosts文件

除了环境变量之外,Docker 还在/etc/hosts文件中添加了源容器的主机条目。这是web容器的条目:

$ docker Run -t -i –RM –link db:webdb training/webapp /Bin/bash

Root@aed84ee21bde:/opt/webapp# cat /etc/hosts

172.17.0.7 aed84ee21bde

172.17.0.5 webdb 6e5cdeb2d300 db

您可以看到两个相关的主机条目。第一个是web使用容器ID作为主机名的容器条目。第二个条目使用链接别名来引用db容器的IP地址。除了您提供的别名之外,链接容器的名称和链接容器的主机名也会被添加到/etc/hosts链接容器的IP地址。您可以通过以下任何条目PING该主机:

Root@aed84ee21bde:/opt/webapp# apt-get install -yQQ inetutils-PING

Root@aed84ee21bde:/opt/webapp# PING webdb

PING webdb (172.17.0.5): 48 data bytes

56 bytes from 172.17.0.5: icmp_seq=0 ttl=64 time=0.267 ms

56 bytes from 172.17.0.5: icmp_seq=1 ttl=64 time=0.250 ms

56 bytes from 172.17.0.5: icmp_seq=2 ttl=64 time=0.256 ms

注意:在示例中,您必须安装,PING因为它最初未包含在容器中。

在这里,您使用该PING命令db通过其主机条目PING容器,该条目解析为172.17.0.5. 您可以使用此主机条目来配置应用程序以使用您的db容器。

如果您重新启动源容器,/etc/hosts链接容器上的文件会自动更新为源容器的新IP地址,从而允许链接通信继续。

$ docker Restart db

db

$ docker Run -t -i –RM –link db:db training/webapp /Bin/bash

Root@aed84ee21bde:/opt/webapp# cat /etc/hosts

172.17.0.7 aed84ee21bde

172.17.0.9 db

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册