14 min read
Docker networking explained: ports and DNS
In one sentence: Each container has its own network: its IP, its ports and its own localhost, which is itself and not your computer. For two containers to talk, you put them on a network you create, where Docker resolves each container's name to its IP. And to reach one from outside, you publish a port, always with 127.0.0.1 in front, so only your computer gets in.
What you will learn
- Explain why localhost inside a container is the container itself, and what fails when DATABASE_URL points there.
- Publish a port only on 127.0.0.1, and explain who -p 3000:3000 opens it to and why on Linux it can bypass the firewall.
- Create a network with docker network create and check that its containers find each other by name.
- Connect the API to PostgreSQL by its name and read the network with docker network inspect.
Before you start, read: 05-volumes.md
The problem
Section titled “The problem”Picture Ana with the API already in an image (lesson 4) and PostgreSQL in a container with its data in a volume (lesson 5). She starts the API with her usual .env, the one with DATABASE_URL=postgres://shop:…@localhost:5432/shop, and asks /health: 503, “The database is not responding.” And PostgreSQL is running.
Luis, meanwhile, has copied docker run -p 3000:3000 from a tutorial. He’s in a café, and anyone on the same Wi-Fi can open the shop on his laptop.
Both problems have the same root: a container has its own network, and Docker decides what goes in and out of it.
The analogy
Section titled “The analogy”The analogy
Think of an office building. Each company has its own switchboard, with its own extensions. If you dial “reception” at company A, A’s reception rings, never B’s, even if they’re on the same floor.
To call another company, you go through the building’s switchboard. In some buildings it only knows numbers: you need the exact extension. In others it has a directory, and it’s enough to say “put me through to Accounting.”
And for someone from the street to come in, you open a door. You can open it to the street, and anyone comes in, or only to the inner hallway, and only people already in the building come in.
The building is your computer; each company, a container; “reception,” localhost; the switchboard with a directory, a network you create; and the door, a published port.
Where the analogy breaks down
- In a building, the switchboard doesn’t change numbers. In Docker, a container’s IP can change every time you create it: that’s why calling it by name matters.
- A door to the hallway is only as safe as the building. With
127.0.0.1, any program on your computer gets in, not just the ones you trust. - On a Mac and on Windows there’s a building inside another: the containers live in Docker Desktop’s virtual machine, and Docker brings the doors all the way to your computer.
How it really works
Section titled “How it really works”Each container has its own network
Section titled “Each container has its own network”The Linux kernel gives each container its own network namespace: its network cards, its IP, its ports and its own 127.0.0.1. It’s the same isolation that separates its processes, the one from the introduction, applied to the network.
Docker connects that namespace to a Docker networkA private network Docker creates inside your computer so containers can talk to each other, each one with its own IP address. On a network you create yourself, with docker network create, each container finds the others by name, because Docker acts as their DNS.Go to definition, a private network inside your computer, with addresses from the 172.16.0.0 to 172.31.255.255 range you saw in lesson 5 of Phase 0. If you don’t name another one, the network is called bridge.
localhost inside a container is the container
Section titled “localhost inside a container is the container”This is what happened to Ana, and what lesson 3 warned about. The outputs in this lesson come from Docker Engine 29 on a Mac, inside a virtual machine running Linux, like Docker Desktop’s. We captured them with other ports and names, swapped for the lesson’s: nothing else changes. Your IDs, IPs and times will be different.
You work in your project’s folder; if the shop container from lesson 4 is still running, delete it first with docker rm -f shop, because it uses the same port.
The API with your usual .env
docker run -d --name api --env-file .env -p 127.0.0.1:3000:3000 shop-apicurl -s localhost:3000/healthWhat you will see:
afdc8efbb1b748d4a68ac7428ae6c7c56443d08e31d526363596088d59291266{"type":"about:blank","title":"Service Unavailable","status":503,"detail":"The database is not responding"}--env-file .env creates a variable inside for each line of your .env, as in lesson 3. Among them, DATABASE_URL, which points to localhost:5432.
The API starts and answers, but its /health route (lesson 4) can’t talk to PostgreSQL. It doesn’t matter that your PostgreSQL is running.
Who answers localhost in there? Ask the API itself. The image doesn’t bring curl, but it brings Node, and its fetch does the same, like the HEALTHCHECK from lesson 4:
Inside the container, localhost is itself
docker exec api node -e "fetch('http://localhost:3000/health').then((r) => r.text()).then(console.log)"docker exec api hostname -iWhat you will see:
{"type":"about:blank","title":"Service Unavailable","status":503,"detail":"The database is not responding"}172.17.0.3node -e "…"runs the code between the quotes: it requestslocalhost:3000/healthand writes the response.- The API itself answers, with its
503:localhostinside the container is the container. hostname -iwrites the container’s IP on thebridgenetwork:172.17.0.3, not your computer’s.
So localhost:5432 inside the container looks for a PostgreSQL in the API’s own container, where there isn’t one.
| From where | localhost is |
|---|---|
| Your terminal | Your computer, where your PostgreSQL from Phase 5 is |
The api container |
The api container, with no PostgreSQL |
The db container |
The db container |
To reach your computer from a container, lesson 3 used the special name host.docker.internal. To reach another container, what you need is a network with names, a bit further down.
Publishing a port opens a door on your computer
Section titled “Publishing a port opens a door on your computer”From outside Docker, you reach a container through a published port. Publishing a portConnecting a port on your computer to a port in a container, with the -p option of docker run, so that whatever reaches the first one goes into the second. Without an IP in front, Docker opens the port on all of your computer’s addresses, and anyone on your network can reach it; with 127.0.0.1 in front, only your computer can.Go to definition is joining one on your computer to one in the container, with -p, as in lesson 1. In -p 127.0.0.1:3000:3000:
127.0.0.1: which address on your computer Docker listens on. This is localhostA name that always means “this same computer.” When you open localhost:8080, both the client and the server are on your machine.Go to definition’s: only programs on your own computer get in.- The first
3000: the PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition on your computer; the second, the container’s, where the API listens.
Inside, the API listens on 0.0.0.0 (ENV HOST=0.0.0.0, lesson 3), because what’s published comes in through the container’s network, not through its 127.0.0.1. Who can get in is decided by the address in -p, not by the API’s.
With no IP in front, the port opens to your whole network
Section titled “With no IP in front, the port opens to your whole network”If you remove 127.0.0.1:, Docker listens on all your computer’s addresses, 0.0.0.0 and [::], like the table in lesson 5 of Phase 0. Check it without opening anything: docker create prepares a container without starting it.
Who each -p opens to
docker create --name open -p 3000:3000 shop-apidocker inspect --format '{{json .HostConfig.PortBindings}}' api opendocker rm openWhat you will see:
681c8a60ba59ee01022b004dc644528881d2f39f82cc473e7f98591d32d856b3{"3000/tcp":[{"HostIp":"127.0.0.1","HostPort":"3000"}]}{"3000/tcp":[{"HostIp":"","HostPort":"3000"}]}openapi is the container from before, still running. docker inspect shows everything Docker knows about a container; --format picks a piece, here its published ports. "HostIp":"", empty, means “all of them”: with docker run, docker ps would show it as 0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp.
With 127.0.0.1, not even your own laptop gets in through its Wi-Fi IP. Find yours with ipconfig getifaddr en0 on a Mac, or hostname -I on Linux:
From the Wi-Fi, you can't get in
curl -sS -m 3 http://192.168.1.133:3000/healthWhat you will see:
curl: (7) Failed to connect to 192.168.1.133 port 3000 after 3 ms: Couldn't connect to server-m 3 stops waiting after three seconds. Nobody listens on the Wi-Fi IP: that’s what you want. With -p 3000:3000, the shop would answer, to you and to anyone in the café. Your IP will be different.
You can delete this container now: docker rm -f api.
Docker’s documentation puts it bluntly: “Publishing container ports is insecure by default.”
On Linux there’s something worse. A firewall is a program that decides which connections to let in; on Ubuntu, the usual one is ufw, and you’ll set it up in Phase 8. Docker publishes ports with its own rules in the kernel, and those rules apply before ufw’s. Docker’s documentation explains it: packets are diverted “before the firewall rules can be applied, effectively ignoring your firewall configuration.” Even if ufw closes port 3000, a -p 3000:3000 leaves it open to the internet on a server.
The course’s rule: always 127.0.0.1: in front. When something has to be public, in Phase 8, a web server in front will decide.
The default network doesn’t know names
Section titled “The default network doesn’t know names”Docker comes with three networks:
Docker's networks
docker network lsWhat you will see:
NETWORK ID NAME DRIVER SCOPEfc409dd26ee2 bridge bridge local662a6ec1c404 host host local612be13019d0 none null localbridgeis the default network: if you don’t name another one, every container joins it.hostremoves the isolation: the container uses the machine’s network. On a Mac, that machine is Docker’s virtual one, not your Mac.none, no network.
DRIVER is the type of network. If you’ve already created other networks, they show up too.
On bridge, containers see each other by IP, but not by name. If you start PostgreSQL with --name db and ask for db from another container, nobody finds it:
On the default network, db doesn't exist
docker run --rm shop-api getent hosts dbecho $?What you will see:
2getent hosts db asks which IP the name db has, as the API does when it connects. It writes nothing: it doesn’t find it. echo $? writes its Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition, and 2 means “that name doesn’t exist.”
Using the IP, 172.17.0.2, would work until you recreate the container and it gets another one.
On your own network, a container’s name is its address
Section titled “On your own network, a container’s name is its address”A network you create with docker network create has something bridge doesn’t: its own DNSDNS stands for Domain Name System.The system that turns names such as example.com into IP addresses (and stores other data about the domain, such as its mail servers). It is a database spread across the whole world, organized as a tree of names.Go to definition. Inside each container, Docker listens on 127.0.0.11 and answers with the IP of any container on the network, by its name. What it doesn’t know, like example.com, it asks outside, to your computer’s DNS, as in lesson 7 of Phase 0.
The bridge network |
A network of your own (docker network create) |
|
|---|---|---|
| Containers find each other | Only by IP | By name |
| Who joins | Everyone that doesn’t name another | Only the ones you start with --network |
| Isolation | They share a network with any container | They only see the ones on their network |
That’s why Docker’s documentation recommends your own networks. The API, with DATABASE_URL=postgres://shop:…@db:5432/shop, asks for db, and Docker answers with whatever IP it has that day.
The full path of a request looks like this:
- curl in your terminallocalhost:3000
-p 127.0.0.1:3000:3000
- api containerlistens on 0.0.0.0:3000
shop network: db is 172.19.0.2
- db containerPostgreSQL on 5432, not published
db doesn’t publish any port: only the containers on its network reach it. Your PostgreSQL from Phase 5 can stay on your computer’s port 5432 without clashing.
Compose creates the network for you
Section titled “Compose creates the network for you”In lesson 7, a compose.yaml file starts the API, PostgreSQL and Redis with one command. Compose creates a network for the project on its own, shop_default, and puts all the services on it, each with its name: db, redis, api. It’s the same thing you’re about to do by hand.
Try it
Section titled “Try it”The goal: get the API to talk to the PostgreSQL from lesson 5 by its name, and find out why a second copy can’t.
You need the shop-api image from lesson 4 (if you don’t have it, docker build -t shop-api . in your project) and the data volume from lesson 5, with your data. If lesson 5’s PostgreSQL container is still running, stop it with docker stop and delete it with docker rm: the volume stays. If lesson 4’s API is still running, delete it with docker rm -f shop.
1. Create the network
docker network create shopWhat you will see:
f202c031fe5594f6eb31a41ef36ebf97f5bbb012e23cf72f917d933ad5356de2The new network’s ID. If you get network with name shop already exists, you already had it: carry on.
2. PostgreSQL, on the network and with its volume
docker run -d --name db --network shop -v data:/var/lib/postgresql postgres:18What you will see:
38d8bd52e7ea84725c7b1e39a87e3f98cb840dc6f9e8c016587bb675ab843e32--name dbis also its name on the network.--network shopputs it on your network, instead of onbridge.-v data:/var/lib/postgresql, the volume from lesson 5, with your data, your user and its password.- No
-e POSTGRES_PASSWORD: the image only uses it the first time, with the volume empty. It’s already saved. - No
-p: nobody outside needs it.
3. Is db found by its name?
docker run --rm --network shop shop-api getent hosts dbWhat you will see:
172.19.0.2 dbNow it is: Docker’s DNS answers with db’s IP. Yours may be different, like 172.18.0.2: there were other networks here. If it writes nothing, db isn’t on shop: go over step 2.
4. The API, on the same network
docker run -d --name api --network shop --env-file .env \ -e DATABASE_URL=postgres://shop:YOUR-PASSWORD@db:5432/shop \ -p 127.0.0.1:3000:3000 shop-apiWhat you will see:
e65c154a2df5dc4e47fc525b8774a9c1c20aa61f8dc48e93b12fbb36bb48fce1Replace YOUR-PASSWORD with the PostgreSQL password from lesson 5. The \ at the end of the line continues the command on the next one.
-e wins over --env-file: your .env keeps localhost, for when you start the API without Docker, and in the container the DATABASE_URL with db is the one that counts.
5. Ask the shop
curl -s localhost:3000/healthdocker psWhat you will see:
{"status":"ok"}CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESe65c154a2df5 shop-api "docker-entrypoint.s…" 17 seconds ago Up 17 seconds (healthy) 127.0.0.1:3000->3000/tcp api38d8bd52e7ea postgres:18 "docker-entrypoint.s…" 26 seconds ago Up 26 seconds 5432/tcp db{"status":"ok"}: the API has talked to PostgreSQL. Look at PORTS. The API has an arrow, 127.0.0.1:3000->3000/tcp: published, only on your computer. db says 5432/tcp, with no arrow: it’s the port it uses inside, not published.
(healthy) shows up after ten seconds, once lesson 4’s HEALTHCHECK has asked /health; before that, (health: starting). If curl says 503, wait a few seconds, in case PostgreSQL is still starting, and then check the password and that both have --network shop.
6. Who answers the names
docker exec api cat /etc/resolv.confWhat you will see:
# Generated by Docker Engine.…nameserver 127.0.0.11options ndots:0…/etc/resolv.conf tells a program which DNS server to ask. Here, 127.0.0.11: Docker’s DNS, inside the container. We’ve trimmed the comments (…).
7. Look inside the network
docker network inspect shopWhat you will see:
[ { "Name": "shop", "Id": "f202c031fe5594f6eb31a41ef36ebf97f5bbb012e23cf72f917d933ad5356de2", "Created": "2026-10-14T07:21:27.272237505+02:00", "Scope": "local", "Driver": "bridge", … "Config": [ { "Subnet": "172.19.0.0/16", "Gateway": "172.19.0.1" } ] … "Containers": { "38d8bd52e7ea84725c7b1e39a87e3f98cb840dc6f9e8c016587bb675ab843e32": { "Name": "db", … "IPv4Address": "172.19.0.2/16", … }, "e65c154a2df5dc4e47fc525b8774a9c1c20aa61f8dc48e93b12fbb36bb48fce1": { "Name": "api", … "IPv4Address": "172.19.0.3/16", … } }, … }]Driver: bridge: it’s the same type as the default network, but yours, with DNS.Subnet: the network’s addresses,172.19.0.0/16, private ones.Gateway,172.19.0.1, is its GatewayThe router your computer sends everything that isn’t for its own local network to. At home it is your router, for example 192.168.1.1.Go to definition, the way out to your computer.Containers: who’s inside and with which IP. If you recreatedb, its IP may change; its name, no.
We’ve trimmed the output (…).
Challenge: start a second API, api2, on port 3001 and with the same DATABASE_URL, but without --network. What does /health answer, and why? Fix it without deleting it.Show answer
docker run -d --name api2 --env-file .env \ -e DATABASE_URL=postgres://shop:YOUR-PASSWORD@db:5432/shop \ -p 127.0.0.1:3001:3000 shop-apicurl -s localhost:3001/healthIt answers 503, “The database is not responding.” api2 is on the bridge network, where nobody knows the name db: docker exec api2 getent hosts db writes nothing.
docker network connect shop api2 connects it to your network without stopping it, and the next curl -s localhost:3001/health says {"status":"ok"}. A container can be on several networks at once.
To finish, clean up. The data volume stays, with your data:
docker rm -f api api2docker stop db && docker rm dbdocker network rm shopdocker stop before rm lets PostgreSQL shut down properly. A network can only be deleted when there are no containers left on it.
You have already seen it
Section titled “You have already seen it”- Your home. The router hands out private IPs to your devices, as in Phase 0. Docker acts as the router for your containers.
- nginx’s
access.login lesson 1. Your requests came from172.17.0.1: thebridgenetwork’s gateway, where whatever reaches a published port comes in. docker ps. ItsPORTScolumn, since lesson 1, tells you what’s published and where.- A website’s development server. Vite only listens on
localhostuntil you ask it for--host, as Phase 0 told you: the same decision as the127.0.0.1:in-p.
Common mistakes
Section titled “Common mistakes”localhostin a container’s configuration. ADATABASE_URLorREDIS_URLwithlocalhostpoints, inside the container, to the container itself. Use the other container’s name, on a network of your own.-p 3000:3000without127.0.0.1:. It opens the port to your whole network and, on a Linux server, to the internet even ifufwsays no.- Expecting names on the default network. If
getent hosts dbwrites nothing, one of the two isn’t on your network: start it with--networkor usedocker network connect. - A server listening on
127.0.0.1inside the container. With-e HOST=127.0.0.1,curl -sS localhost:3000/healthsayscurl: (52) Empty reply from server: the port is published, but inside nobody listens on the container’s network. Inside,0.0.0.0. - Publishing the database port “just in case.”
-p 5432:5432opens your database to your whole network, and it can clash with port 5432 of your PostgreSQL from Phase 5. The API reachesdbthrough Docker’s network without publishing anything.
Summary
Section titled “Summary”- Each container has its own network: its IP, its ports and its
localhost, which is itself. - Publishing a port with
-popens a door from outside. With no IP in front, it opens on all your computer’s addresses and, on Linux, bypassesufw: always127.0.0.1:in front. - On the default network,
bridge, containers don’t find each other by name. On a network of your own, made withdocker network create, Docker resolves each name to its IP. - The API reaches PostgreSQL with
DATABASE_URL=postgres://shop:…@db:5432/shop, anddbdoesn’t need any published port. docker network inspecttells you who’s on a network and with which IP. In lesson 7, Compose creates that network for you.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Networking overview, from Docker’s documentation: the types of network and how containers connect.
- Port publishing and mapping: why publishing is insecure by default, and how to change the address Docker uses when you don’t name one.
- Docker with iptables and ufw: why Docker and
ufwdon’t get along. - Bridge network driver: the differences between the default network and your own.