CodeBlanks Logo Icon CodeBlanks

Publishing ports

Learn to publish ports on a network.

Port publishing and internal traffic

Containers on the same network reach each other directly through the container port; publishing a port is only for the host and the outside world. That is why the container port, not the host port, is used in connection addresses:

docker run -d --name db --network arka -p 15432:5432 postgres:16
# from the host:          psql -h localhost -p 15432
# api on the arka network: postgresql://db:5432/app     (not 15432!)

The reverse proxy pattern

A common layout: only a reverse proxy (nginx, Traefik, Caddy) publishes 80/443 and forwards requests to services inside the network by service name. The application and database publish no ports:

# nginx.conf
location /api/ {
    proxy_pass http://api:8000/;
}

docker run -d --name vekil --network on -p 80:80 -v "$PWD/nginx.conf":/etc/nginx/conf.d/default.conf:ro nginx

Practice A proxied setup

Write two commands: start a container named api from api:1.0 in the background on the on network without publishing ports; start a container named vekil from nginx in the background on the on network, mapping 80 to 80 and mounting "$PWD/nginx.conf" read-only at /etc/nginx/conf.d/default.conf.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker run -d --name api --network on api:1.0
docker run -d --name vekil --network on -p 80:80 -v "$PWD/nginx.conf":/etc/nginx/conf.d/default.conf:ro nginx

Expected output

091a2b3c4d5e
1a2b3c4d5e6f

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If db is published with -p 15432:5432, which address should api on the same network connect to?

  • db:5432 Correct answer
  • db:15432
  • localhost:15432
  • localhost:5432

Explanation: Inside a container, localhost is the container itself.

2 Forward the request to the api service.

Question
location /api/ {
    proxy_pass http://____:8000/;
}
Answer
location /api/ {
    proxy_pass http://api:8000/;
}

Explanation: The service name on the network is the DNS name.

3 Match.

Term Meaning
container port In-network traffic
published port Host and outside world
reverse proxy Single entry point
localhost (inside the container) The container itself

All lessons in Beginner