I've had db and server container, both running in the same network. Can ping db host by its container id with no problem.
When I set a hostname for db container manually (-h myname
), it had an effect ($ hostname
returns set host), but I can't ping that hostname from another container in the same network. Container id still pingable.
Although it works with no problem in docker compose.
What am I missing?
相关问题
- Docker task in Azure devops won't accept "$(pw
- Unable to run mariadb when mount volume
- Unspecified error (0x80004005) while running a Doc
- What would prevent code running in a Docker contai
- How to reload apache in php-apache docker containe
I've found out, that problem can be solved without network using --add-host option. Container's IP can be gain using inspect command.
But when containers in the same network, they are able to access each other via it names.
As stated in the docker docs, if you start containers on the default bridge network, adding
-h myname
will add this information toof the container just started.
However, this will not have any effect to other independent containers. (You could use
--link
to add this information to /etc/hosts of other containers. However,--link
is deprecated.)On the other hand, when you create a user-defined bridge network, docker provides an embedded DNS server to make name lookups between containers on that network possible, see Embedded DNS server in user-defined networks. Name resolution takes the container names defined with
--name
. (You will not find another container by using its--hostname
value.)The reason, why it works with docker-compose is, that docker-compose creates a custom network for you and automatically names the containers.
The situation seems to be a bit different, when you don't specify a name for the container yourself. The run reference says
In agreement with your findings, this should be read as: If you don't specify a custom
--name
, you cannot use the auto-generated name to look up other containers on the same network.Hostname is not used by docker's built in DNS service. It's a counterintuitive exception, but since hostnames can change outside of docker's control, it makes some sense. Docker's DNS will resolve:
The easiest of these options is the last one which is automatically configured when running containers with a compose file. The service name itself is a network alias. This lets you scale and perform rolling updates without reconfiguring other containers.
You need to be on a user created network, not something like the default bridge which has DNS disabled. This is done by default when running containers with a compose file.
Avoid using links since they are deprecated. And I'd only recommend adding host entries for external static hosts that are not in any DNS, for container to container, or access to other hosts outside of docker, DNS is preferred.