Using ping
with a service name might not do what you expect. What you may want to do is ping the container name. For example, ping bar_bar_run_45964b29fb9a
from foo would probably work.
In simple use cases it’s easy to assume services == containers but docker-compose.yml files can be used with docker stack
commands which include things like number of replicas
where you might have 3 instances of foo running and in that case, ping foo
would not know which instance to ping.
However, a slight gotcha - pinging via container name won’t work on the default network, you’ll need to create your own. See https://docs.docker.com/v17.09/engine/userguide/networking/work-with-networks/#basic-container-networking-example section 8 (This functionality is not available for the default bridge network. Both container1 and container2 are connected to the bridge network, but you cannot ping container1 from container2 using the container name.)
You can also find the IP address of the container you wish to ping and ping the IP address directly you will probably see that it works. (In your example, ping 172.28.0.3
from foo to bar, and ping 172.28.0.2
from bar to foo.)
When you are using higher level networking commands such as HTTP requests the DNS service-to-service resolution will work as expected so you can still connect to other services via the service name, just not ping
You are probably aware of this already but this sort of setup is easier if you put both services in the same docker-compose.yml file and then you only need to docker-compose up
once. They will both join the default network without you needing to define anything.