Docker module
Lesson 9
Publish ports
Container ports versus host ports, -p, and why Postgres is unreachable until you publish it.
beginner25 minRun on your machine
What you will be able to do
- Publish a container port to the host with -p
- Reach nginx on localhost from your terminal
- Explain the difference between EXPOSE and -p
Why this matters for DE and AI
Postgres inside a container listens on 5432 in the container network. Your laptop’s psql or a GUI talks to a port on the host. Until you publish (-p 15432:5432), the database is only visible to other containers on the same Docker network — which is often what you want in Compose, and a surprise when you expected localhost.
Concepts
docker run -p HOSTPORT:CONTAINERPORT IMAGE
-p 18080:80 means: on the host, port 18080 forwards to port 80 inside the container (nginx’s HTTP).
We use 18080 in this module so we do not fight with common local apps on 8080, or with this site’s own lab port 8088.
EXPOSE 80 in a Dockerfile is documentation. It does not publish the port. Only -p / Compose ports: does.
From another container you do not use localhost. You use the service name on the Compose network (db:5432). localhost inside a container is that container itself. This mix-up is a weekly ticket.
your terminal --> 127.0.0.1:HOSTPORT --> container:CONTAINERPORT
other container --> servicename:CONTAINERPORT (Compose network)
Practice on your machine
cd ~/dcubes/docker-lab
docker pull nginx:1.27-alpine
docker run -d --name dcubes-web -p 18080:80 nginx:1.27-alpine
docker ps --filter name=dcubes-web
What you should see: ports like 0.0.0.0:18080->80/tcp.
curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:18080
What you should see: 200
Print a bit of the default page:
curl -sS http://127.0.0.1:18080 | head
You should see HTML that mentions nginx.
If curl fails with connection refused, the container is not up or the host port is wrong. docker logs dcubes-web and docker ps.
Stop and remove:
docker stop dcubes-web
docker rm dcubes-web
curl to the same URL should now fail. The publish died with the container.
Common mistakes
-p 80:18080reversed. Left is host, right is container. nginx listens on 80 inside.- Using
localhostfrom a second container to reach the first. Use the Compose service name instead. - Assuming EXPOSE opened the firewall. It did not.
Next
Environment in containers — -e, env files, and secrets that must not live in the image.