docker run --name vs --hostname difference as command line option (ping: bad address)
1. docker
2.为什么
创建网络和连接到它的两个容器:
1 2 3 | docker network create test docker run --rm -dit --name bar --network test --hostname barhost alpine:latest docker run --rm -it --name foo --network test --hostname foohost alpine:latest |
从
1 | ping -c2 barhost |
给出结果:
bad address 'barhost'
但是从
1 | ping -c2 bar |
成功:
PING bar (172.31.0.2): 56 data bytes 64 bytes from 172.31.0.2: seq=0
ttl=64 time=0.260 ms 64 bytes from 172.31.0.2: seq=1 ttl=64 time=0.155
ms--- bar ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss
3.如果你无法通过
1 2 | # assuming you've created network test from point 2. docker run --rm -it --name bar --network test --hostname barhost alpine:latest |
从
1 | ping -c2 barhost |
成功:
PING barhost (172.31.0.2): 56 data bytes 64 bytes from 172.31.0.2:
seq=0 ttl=64 time=0.135 ms 64 bytes from 172.31.0.2: seq=1 ttl=64
time=0.127 ms--- barhost ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss
1.What is the difference between --name and --hostname in docker run command?
答:当我们使用
所以我们可以在docker run命令中使用
类似地,当创建docker容器时,hostname默认为Docker中容器的ID。您可以使用
现在考虑一个场景,你通过代码使用docker容器,并且你想引用docker。由于在创建时生成了docke rid,因此您无法事先知道它,因此您可以使用--name。要知道何时在docker run中使用--hostname,请从此stackoverflow帖子中读取
2.Why foo can't reach bar by its hostname = barhost ?
答案:正如上面提到的stackoverflow post中所指定的那样,
3.If you can't reach bar by its hostname from foo why it is possible to do that from within bar?
答:现在必须明确答案。在容器内部,使用