Container networking
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 webUser-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 onappnetcan reach it. - Publish with
-p 127.0.0.1:8080:80to listen only on the local machine. - Inside a container,
localhostmeans 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 appnetTest yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.