Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 111 ยท Networking

Publishing Ports

Learn every form of docker run -p, how host IP binding works, what -P and EXPOSE really do, how to debug unreachable ports, and why 0.0.0.0 exposes your service.

A container on a bridge network has a private address that only the Docker host and other containers can reach. To let your browser, a colleague, or the internet talk to a service inside it, you must publish a port: tell Docker to listen on a port of the host and forward the traffic to a port of the container. The flag is -p (or --publish), and it looks simple, which is why so many people use it without noticing that the default form opens the service to every network the machine is connected to.

This lesson covers all the forms of -p, what each one does, how -P and EXPOSE fit in, the most common reasons "the port is published but I get nothing", and the security rule to remember: publish on 127.0.0.1 unless you really mean to publish to the world.

The basic form

TEXT
-p [host_ip:]host_port:container_port[/protocol]

Docker listens on host_port and forwards each connection to container_port of the container. The host side comes first: think "host:container".

CONSOLE
$ docker run -d --name web -p 127.0.0.1:18711:80 nginx:alpine
$ curl -s -o /dev/null -w '%{http_code}\n' 127.0.0.1:18711
200

Traffic to port 18711 of the host reaches nginx on port 80 in the container. The container's port does not need to match the host's. You can run ten nginx containers, each with container port 80, and map them to ten different host ports.

TEXT
  browser โ”€โ”€โ–ถ 127.0.0.1:18711  โ”€โ”€(Docker forwards)โ”€โ”€โ–ถ  container 172.17.0.x:80
              host port                                   container port

All the forms of -p

Here are the variations, each started for real on this machine. docker ps shows the result in its PORTS column:

CONSOLE
$ docker run -d --name p1 -p 127.0.0.1:18711:80 nginx:alpine
$ docker run -d --name p2 -p 18712:80 nginx:alpine
$ docker run -d --name p3 -p 127.0.0.1::80 nginx:alpine
$ docker run -d --name p4 -p 127.0.0.1:18714:80/tcp -p 127.0.0.1:18715:80 nginx:alpine
$ docker run -d --name p5 -p 127.0.0.1:18716-18717:80-81 alpine sleep 300
$ docker ps --format 'table {{.Names}}\t{{.Ports}}'
NAMES   PORTS
p5      127.0.0.1:18716->80/tcp, 127.0.0.1:18717->81/tcp
p4      127.0.0.1:18714->80/tcp, 127.0.0.1:18715->80/tcp
p3      127.0.0.1:59450->80/tcp
p2      0.0.0.0:18712->80/tcp, [::]:18712->80/tcp
p1      127.0.0.1:18711->80/tcp
You write Meaning
-p 18711:80 Host port 18711 on all interfaces (0.0.0.0 and IPv6 ::) to container port 80
-p 127.0.0.1:18711:80 Same, but only reachable from the host itself
-p 127.0.0.1::80 Container port 80 on a random free host port, loopback only (here 59450)
-p 80 Same as above on all interfaces with a random port
-p 18714:80/tcp Protocol explicit; tcp is the default
-p 5353:53/udp UDP instead of TCP (DNS, game servers, syslog)
-p 18716-18717:80-81 A range of ports mapped one to one (ranges must be the same size)
-p 18714:80 -p 18715:80 Several host ports to the same container port, or several ports at once

For a random port, ask Docker which one it picked:

CONSOLE
$ docker port p3
80/tcp -> 127.0.0.1:59450
$ docker port p4
80/tcp -> 127.0.0.1:18714
80/tcp -> 127.0.0.1:18715

The long syntax of --publish is also available in Compose, with names for each field:

YAML
services:
  web:
    image: nginx:alpine
    ports:
      - "127.0.0.1:8080:80"          # short form
      - target: 80                   # long form
        published: "8081"
        host_ip: 127.0.0.1
        protocol: tcp

Always quote the short form in YAML: a bare 8080:80 can be misread by older parsers as a base-60 number in some cases, and quotes cost nothing.

0.0.0.0 and why it matters

Look at container p2 in the listing above: 0.0.0.0:18712->80/tcp, [::]:18712->80/tcp. A -p without an IP address binds to every network interface of the host: Ethernet, Wi-Fi, VPN, and the public interface of a server. Anyone who can reach the machine can reach that port.

CONSOLE
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:18712
200

That request came from the same machine, but a request to the machine's LAN address would also succeed. Compare with p1, bound to 127.0.0.1: only programs on the host can connect.

Why this is a security issue:

  • A database published with -p 5432:5432 is open to the whole network, with whatever password you set, or none.
  • On a cloud server with a public IP, the port is open to the entire internet unless a separate network firewall (cloud security group) blocks it.
  • Docker inserts its own firewall rules for published ports, and on Linux they are evaluated before the rules of tools like ufw or firewalld. A rule such as "deny incoming on 5432" in ufw may not stop traffic to a published container port. How exactly depends on version and configuration, so test from another machine instead of trusting the firewall's status output. See DNS, Proxies and Firewalls.

The rule of thumb:

Publish on 127.0.0.1 by default: -p 127.0.0.1:5432:5432. Only omit the IP address for services that must be reachable from other machines, such as a public web server, and keep everything else (databases, caches, admin tools) off the host entirely by putting them on a user-defined network where only your other containers can reach them.

The best publication for a database is often no publication at all. The application container reaches it through the Docker network by name, and no port on the host is involved. You publish the database only when a tool on your own machine, such as a SQL client, needs it, and then on loopback.

Conflicts: the port is already in use

A host port can have only one listener. Trying to use it twice fails:

CONSOLE
$ docker run -d --name p6 -p 127.0.0.1:18711:80 nginx:alpine
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint p6 (0b9224919577...): Bind for 127.0.0.1:18711 failed: port is already allocated

The container p6 was created but did not start; remove it with docker rm p6. The "already allocated" message means another Docker container owns the port. If a program that is not a container owns it, the message says "address already in use". On Windows, a port inside a range reserved by the system gives "permission denied" instead; pick another one. Find the owner with docker ps first, then ss -ltnp (Linux), lsof -i :PORT (macOS) or netstat -ano (Windows).

-P and EXPOSE

-P (capital) publishes every exposed port of the image to a random host port on all interfaces. A port is "exposed" when the image's EXPOSE instruction or the --expose flag declares it.

CONSOLE
$ docker run -d --name p12 -P nginx:alpine
$ docker ps --format '{{.Ports}}' --filter name=p12
0.0.0.0:32770->80/tcp
$ docker port p12
80/tcp -> 0.0.0.0:32770

It is convenient for quick experiments, but the port number changes every time and, like -p without an IP, it opens all interfaces. Do not use it for anything you keep.

EXPOSE itself publishes nothing. It is metadata, a statement by the image author: "this program listens on port 80". The metadata is stored in the image configuration and displayed by tools:

CONSOLE
$ docker inspect -f '{{json .Config.ExposedPorts}}' p12
{"80/tcp":{}}

A container whose port is only exposed is reachable by other containers on the same network (exposed or not: Docker does not firewall ports between containers on one bridge), but not from outside the host:

CONSOLE
$ docker run -d --name p8 --expose 80 nginx:alpine
$ docker ps --filter name=p8 --format '{{.Ports}}'
80/tcp

The listing shows 80/tcp without an arrow: no host port is bound. So EXPOSE is documentation and an input for -P; -p is what opens a port. For the Dockerfile side, see WORKDIR, USER, EXPOSE and LABEL.

Publishing UDP

TCP is the default; add /udp for UDP services:

CONSOLE
$ docker run -d --name p9 -p 127.0.0.1:18719:8080/udp alpine sleep 300
$ docker ps --filter name=p9 --format '{{.Ports}}'
127.0.0.1:18719->8080/udp

To publish the same port for both protocols, write two flags: -p 53:53/tcp -p 53:53/udp.

"I published the port but nothing answers"

Three causes cover most cases. Work through them in this order.

1. Nothing listens on that container port. Docker's forwarder accepts the connection even if the container has no listener, so you do not get "connection refused". You get an empty answer:

CONSOLE
$ docker run -d --name p10 -p 127.0.0.1:18720:8080 nginx:alpine
$ curl -sS 127.0.0.1:18720
curl: (52) Empty reply from server

nginx listens on 80, not 8080. "Empty reply from server" (or a reset or a hang) usually means: right host port, wrong container port. Check with docker exec p10 netstat -ltn or the image documentation.

2. The application listens only on the container's loopback. A server bound to 127.0.0.1 inside the container is invisible to the outside, even to Docker's forwarding, because traffic arrives on the container's eth0. Same symptom:

CONSOLE
$ docker run -d --name p11 -p 127.0.0.1:18721:9000 alpine nc -l -p 9000 -s 127.0.0.1
$ curl -sS -m 3 127.0.0.1:18721
curl: (52) Empty reply from server

Fix the application to listen on 0.0.0.0 (or ::): flask run --host 0.0.0.0, uvicorn --host 0.0.0.0, server.listen(3000, '0.0.0.0'), bind-address = 0.0.0.0. This is the number one cause of "works outside Docker, not inside".

3. The wrong side of the colon. -p 80:8080 publishes host port 80 to container port 8080, which is the reverse of what many people mean. When in doubt, run docker port <name> and read the arrow.

Other things to check: docker ps must show the container as Up (published ports disappear on exit), the firewall of the machine you connect from, and whether you are using localhost correctly. On Docker Desktop, a port published on 127.0.0.1 is forwarded to your Windows or macOS machine, so localhost:PORT works there too.

A container reaching a published port of the host

A container can connect to the host's published ports through the host's gateway address. On Linux that is the bridge gateway (172.17.0.1); portable setups map a name to it:

CONSOLE
$ docker run -d --name p13 -p 127.0.0.1:18722:80 nginx:alpine
$ docker run --rm --add-host=host.docker.internal:host-gateway alpine wget -qO- -T3 http://host.docker.internal:18722
<!DOCTYPE html>
<html>
<head>

Only use this for talking to something on the host. For container-to-container traffic there is no need to publish anything; see Containers Talking to Each Other.

When to publish, when not

Situation Do this
Local development, you open the app in a browser -p 127.0.0.1:8080:3000
Public web server -p 80:80 -p 443:443, behind a firewall that you tested
Database used by other containers No -p; use a shared network
Database for your SQL client -p 127.0.0.1:5432:5432
Quick experiment where the port number does not matter -P (then docker port)
Production with a reverse proxy Publish only the proxy; everything else stays internal

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -p 8080:80 mean?

    The order is host:container. Without an IP address the port is bound on every host interface (0.0.0.0 and ::).
  2. 2. Which command makes a service reachable only from the machine running Docker?

    Adding 127.0.0.1 binds the host port on the loopback interface only. -p without an IP and -P bind all interfaces, and --expose publishes nothing.
  3. 3. What does the EXPOSE 80 instruction in a Dockerfile do by itself?

    EXPOSE is documentation plus an input for -P. Only -p/-P bind a host port.
  4. 4. You run curl 127.0.0.1:18720 against a published port and get Empty reply from server. Which is a likely cause?

    Docker's forwarder accepts the connection even if the application is not reachable on that container port. Check the port after the colon and make the app listen on 0.0.0.0.
  5. 5. Why is -p 5432:5432 for a database on a public server risky?

    Publish databases on 127.0.0.1 or not at all, and put them on an internal Docker network. Never rely only on ufw status; test from another machine.

Summary

  • -p [ip:]host_port:container_port[/proto] forwards a host port to a container port; the host side comes first.
  • Without an IP address, -p listens on all interfaces; use 127.0.0.1: to keep a port private, and prefer not publishing databases at all.
  • -P publishes every EXPOSEd port to a random host port; docker port NAME shows the result.
  • EXPOSE and --expose are metadata; they publish nothing.
  • "Empty reply" or a hang usually means the wrong container port, or an app bound to the container's loopback; make it listen on 0.0.0.0.
  • Docker's firewall rules can bypass tools like ufw, so test exposure from another machine.

Next: User-Defined Bridge Networks