How to ping Docker container from another container by name?

August 27, 2019 396 views
Docker Linux Basics Networking Ubuntu

Hi all,

I want to be able to ping or basically access a running docker container from another container by simply using the docker name rather than an IP address. I’ve tried a few guides but I could not get it working. Has anyone been able to get this working?

Thanks a lot!

1 Answer
bobbyiliev MOD August 27, 2019
Accepted Answer

Hello,

Yes this now comes more or less out of the box with Docker Networks, so what you need to do is:

  • Create two containers:
docker run -d --name web1  -p 8001:80 eboraas/apache-php
docker run -d --name web2  -p 8002:80 eboraas/apache-php
  • Important note: it is very important to explicitly specify a name with --name for your containers otherwise I’ve noticed that it would not work with the random names that Docker assigns to your containers.

  • Then create a new network:

docker network create myNetwork
  • After that connect your containers to the network:
docker network connect myNetwork web1
docker network connect myNetwork web2 
  • Check if your containers are part of the new network:
docker network inspect myNetwork
  • Then test the connection:
docker exec -ti web1 ping web2

Again it is quite important to explicitly specify names for your containers otherwise this would not work. I figured this out after spending a few hours trying to figure it out.

Hope that this helps!
Regards,
Bobby

Have another answer? Share your knowledge.