CodeBlanks Logo Icon CodeBlanks

The port concept

Learn the relationship between host and container ports.

The port concept

Each container has its own network stack. nginx listening on port 80 inside the container doesn't automatically open port 80 on the host; it can't be reached from outside. For access, the container port is published to a port on the host (port mapping):

host:8080  ──►  container:80
docker run -d -p 8080:80 nginx
curl http://localhost:8080      # the nginx welcome page

Seeing published ports

The PORTS column of docker ps and the docker port command show the published mappings:

$ docker ps --format '{{.Names}} {{.Ports}}'
web 0.0.0.0:8080->80/tcp
$ docker port web
80/tcp -> 0.0.0.0:8080

0.0.0.0 means it listens on all of the host's network interfaces: another computer on the same network can reach it too.

Practice Publish a web server

Write two commands: start a container named web from nginx in the background, mapping host port 8080 to container port 80; then show its port mappings.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker run -d --name web -p 8080:80 nginx
docker port web

Expected output

5a6b7c8d9e0f
80/tcp -> 0.0.0.0:8080

Questions and answers

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

1 Does writing EXPOSE 80 in the Dockerfile provide access from outside?

  • Only on Linux
  • Only for port 80
  • No; it only documents, -p is needed to publish Correct answer
  • Yes, always

Explanation: EXPOSE also tells which ports the -P flag will publish.

2 Show the container's port mappings.

Question
docker ____ web
Answer
docker port web

Explanation: docker port container lists the mappings.

3 Match.

Term Meaning
container port What the app listens on
ana makine portu Reached from outside
EXPOSE Documentation
0.0.0.0 All interfaces

All lessons in Beginner