Recurring docker networking problems

Summary of common docker network questions I have to answer every few months.

These problems are:

  • How to access one container from another container running on the same machine
  • Access a service running in a local container
  • From a running local container access a service running in the system localhost

Having two containers talk to each other

To have containers talk to each other they need to be on the same bridge network. By default, ie if not providing any network, a container will be attached to the default bridge network. So by default they will be able to talk to each other. They can call each other using their ips.

The ips can be obtained by inspecting the bridge network

docker network inspect bride

Be aware of the following comment from the docker documentation:

Dont use default bridge network for production

Service discovery

With a user-defined bridge network automatic service discovery is enabled, which lets containers ping each other using their ip and also their container names.

A bridge network can be created with:

docker network create --driver bridge my-service-net

The official docs provide more details.

Sharing the machine local network

To have containers available under localhost just need to run them with the network host argument. This is the same for having containers access other services running on localhost.

Note that this solution does not work if you are running docker desktop (default for Mac and Windows)

For example:

docker run --rm -d --network host --name my_nginx nginx

Now nginx can be accessed on the browser by going to localhost:80

Access localhost from a container

After running the nginx container, run on the local machine a python server:

python3.7 -m http.server

Now log into the nginx container and curl localhost, the python server will show the request.

For more details see the official docs