appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Container networking

Lesson 3 of 411 minIntermediate

How containers find each other, and how the outside world reaches them.

By default containers sit on a private bridge network. To reach a container from outside you publish a port: -p HOST:CONTAINER.

docker run -d --name web -p 8080:80 nginx   # host 8080 -> container 80
docker port web

User-defined networks give you DNS

On a network you create yourself, containers reach each other by name. On the default bridge they do not. Create one network per application.

docker network create appnet
docker run -d --name db --network appnet -e POSTGRES_PASSWORD=secret postgres:16
docker run -d --name api --network appnet -e DB_HOST=db myapi
# inside api, the database is reachable at the hostname "db"

Publish only what you need

  • The database in the example has no -p. Only containers on appnet can reach it.
  • Publish with -p 127.0.0.1:8080:80 to listen only on the local machine.
  • Inside a container, localhost means the container itself, not the host.

CarefulDocker edits the host firewall rules to publish ports and this can bypass rules written in ufw. A published port is reachable from the network unless you bind it to 127.0.0.1.

docker network ls
docker network inspect appnet

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. How can two containers on the same user-defined network reach each other?
2. Inside a container, what does localhost refer to?
Hintdocker network create ...

Key terms