Docker Tutorial · Data and Networking · Lesson 18 of 26

Publishing Ports

Make a container reachable from the host and the outside world with -p, and bind to localhost when you mean it.

Create a free account to save this page, take notes and track your progress. Sign in

-p HOST:CONTAINER

Containers on a bridge network aren't reachable from outside by default. -p 8080:80 forwards host port 8080 to container port 80. Forms worth knowing:

Option Meaning
-p 8080:80 All host interfaces, port 8080
-p 127.0.0.1:8080:80 Only from the host itself (safer for databases and admin tools)
-p 80 A random free host port (see docker port)

Published ports bypass some host firewall setups (Docker manages its own iptables rules), so binding databases to 127.0.0.1 matters on servers.

Serve a page on localhost:18080
trap 'docker rm -f rc-web > /dev/null 2>&1' EXIT
mkdir site && echo "<h1>Hello from nginx</h1>" > site/index.html
docker run -d --name rc-web -p 127.0.0.1:18080:80 -v "$PWD/site:/usr/share/nginx/html:ro" nginx:1.29-alpine > /dev/null
for i in 1 2 3 4 5; do curl -sf http://127.0.0.1:18080/ > /dev/null && break; sleep 1; done
curl -s http://127.0.0.1:18080/
echo "published: $(docker port rc-web 80/tcp)"

Output

<h1>Hello from nginx</h1>
published: 127.0.0.1:18080

Run this on your computer — see “Get Started” for setup.

Test yourself

How do you publish a database port only to the host itself?

  1. -p 5432:5432
  2. -p 127.0.0.1:5432:5432
  3. EXPOSE 5432
  4. --network host
Show answer

Answer: -p 127.0.0.1:5432:5432

Binding to 127.0.0.1 keeps the port off external interfaces.

Was this page helpful?