7
votes

1.What is the difference between --name and --hostname in docker run command?

2.Why foo can't reach bar by its hostname = barhost ?

create network and two containers connected to it:

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

ping barhost from foo terminal

ping -c2 barhost

gives result:

bad address 'barhost'

but ping bar from foo

ping -c2 bar

is successful:

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.If you can't reach bar by its hostname from foo why it is possible to do that from within bar?

# assuming you've created network test from point 2.
docker run --rm -it --name bar --network test --hostname barhost alpine:latest

ping barhost from bar terminal

ping -c2 barhost

is successful:

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

1 Answers

9
votes

1.What is the difference between --name and --hostname in docker run command?

Answer: When we use docker run command docker creates a container and assigns a Container Id of type UUID to it. Now this Container Id can be used to refer to the container created. But remembering this Container Id can be difficult.

So we can use --name in docker run command. Now you can either use the Container Id to refer to the container created or can use the container name for the same.

Similarly when docker container is created the hostname defaults to be the container’s ID in Docker. You can override the hostname using --hostname. I have taken this from Docker docs.

Now consider a scenario where you are making use of docker containers through code and you want to refer to docker. Since docke rid is generated at the time of creation you can't know it in advance so you can use --name. To know when to use --hostname in docker run read from this stackoverflow post

2.Why foo can't reach bar by its hostname = barhost ?

Answer: As specified in the above mentioned stackoverflow post the --hostname doesn't literally change the hostname for docker container such that same can be used to access it from outside. It's use case is similar to why would you want to use --name flag that is you are expecting a certain value which otherwise is generated at the time of container creation.

3.If you can't reach bar by its hostname from foo why it is possible to do that from within bar?

Answer: The answer to this must be clear by now. Inside the container the hostname mentioned using --hostname exists but it is not true outside of the container.