Publishing ports

How to make a service in a container reachable from outside.

A container has its own network. A server listening on port 80 inside a container is not reachable from the host by default: the port has to be published. The -p 8080:80 flag connects port 8080 on the host to port 80 in the container. The host port always comes first, then the container port.

docker run -d --name site -p 8080:80 nginx:1.27
curl http://localhost:8080
docker port site
# 80/tcp -> 0.0.0.0:8080

A request to port 8080 on the host reaches port 80 in the container. docker port shows which ports are published.

By default a published port listens on all of the host's network interfaces, so it is reachable from the network, not only from your computer. To make a port visible only locally, add an address: -p 127.0.0.1:8080:80. This matters for databases and admin panels: a database open to the outside is a frequent cause of leaks. Also keep in mind that on Linux Docker's rules for published ports can bypass the settings of a simple firewall, so it is better not to publish anything extra than to rely on the firewall.

The EXPOSE 80 instruction in a Dockerfile does not publish a port. It is documentation: it says which port the application listens on. All such ports can be published to random host ports with the -P flag, but in practice -p is usually given explicitly.

A common mistake is an application inside the container listening on 127.0.0.1. It then accepts connections only from inside the container itself, and the published port is useless: the connection drops. A server in a container must listen on 0.0.0.0, and access is restricted on the publishing side.

Practice

  1. Order in -p

    What does -p 3000:8000 mean?

    • Container port 3000 is reachable on host port 8000
    • Container port 8000 is reachable on host port 3000
    • The container may use ports 3000 to 8000
    • A rate limit of 3000 out of 8000 requests
  2. Ports and access

    Which statements are true? Mark all.

    • EXPOSE in a Dockerfile publishes the port on the host
    • -p 127.0.0.1:5432:5432 opens the port only to the local machine
    • A server in a container must listen on 0.0.0.0 for a published port to work
    • Without -p a container port is not reachable from the host by default
  3. Where to send requests

    A container was started with -p 9090:3000. Which host port do you send requests to? Answer with a number.