Docker port mapping, EXPOSE, and host networking explained
Why Dockerfile EXPOSE does not open ports, how -p creates iptables DNAT rules, why 0.0.0.0 bypasses UFW, and when to avoid host networking.
Adding
EXPOSE 8080to a Dockerfile doesn’t publish a port to your host, while-p 8080:80quietly bypasses UFW by writingiptablesDNAT rules. This post breaks down how Docker publishes ports at the Linux kernel level, where0.0.0.0binding creates security holes, and when--network hostdoes more harm than good.
One of the first headaches you hit with Docker is seeing Tomcat started on port 8080 in your container logs, checking that EXPOSE 8080 is in your Dockerfile, and still getting Connection refused at http://localhost:8080.
The confusion disappears once you see how Docker interacts with Linux network namespaces and iptables. Let’s walk through what EXPOSE actually does, how -p forwards packets through DNAT and docker-proxy, how --network host trades isolation for throughput, and why default 0.0.0.0 publishing can expose internal databases straight to the public internet.
1. What EXPOSE actually does (and doesn’t do)
Many developers assume EXPOSE opens a firewall port like ufw allow or makes a process listen on that port. It does neither.
EXPOSE never opens a host or container port and never changes packet routing.
1
2
3
4
5
6
7
8
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY build/libs/api-server.jar app.jar
# Metadata only — does NOT publish or bind any port on the host
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
EXPOSE is image metadata
As Docker’s documentation states, EXPOSE is a documentation contract between the person building the image and the person running the container. Inspect a built image and you’ll see it stored as a plain JSON key:
1
2
3
4
$ docker inspect my-api-server:latest | jq '.[0].Config.ExposedPorts'
{
"8080/tcp": {}
}
No socket is bound and no firewall rule is created.
The one runtime effect: -P (--publish-all)
The only time Docker acts on EXPOSE at runtime is when you pass uppercase -P:
1
2
3
$ docker run -d -P --name my-app my-api-server:latest
$ docker port my-app
8080/tcp -> 0.0.0.0:32768
Uppercase -P maps every exposed port to a random port in the host’s ephemeral range (typically 32768–60999).
Production deployments can’t depend on random ports that change on every restart. Treat
-Pas a quick local test flag and always use lowercase-p(--publish) for explicit port bindings.
2. Under the hood of -p 8080:80: iptables DNAT and docker-proxy
To reach a container port from the host or external network, publish it explicitly with -p <host-port>:<container-port>:
1
docker run -d -p 8080:80 --name web-nginx nginx:alpine
Under the hood, Docker wires up two mechanisms on the Linux host.
flowchart TD
Client["External Client Packet<br/>(Dst: Host-IP:8080)"] --> Eth0["Host eth0 Interface"]
Eth0 --> PREROUTING["iptables PREROUTING Chain"]
PREROUTING --> DOCKER_CHAIN["DOCKER Chain (DNAT)"]
DOCKER_CHAIN -->|"Rewrite Dst to 172.17.0.2:80"| Docker0["docker0 Bridge"]
Docker0 --> Veth["veth pair"]
Veth --> Container["Container eth0<br/>(Nginx listening on 80)"]
LocalClient["Host Local Process<br/>(localhost:8080)"] -.-> DockerProxy["docker-proxy<br/>(User-space relay)"]
DockerProxy -.-> Container
1) Kernel-level iptables DNAT
The Docker daemon injects its own DOCKER chain into Linux netfilter/iptables. Any packet arriving on host port 8080 has its destination IP and port rewritten via DNAT (Destination NAT) to the container’s private IP and port (172.17.0.2:80).
You can verify the exact rule on the host:
1
2
3
4
5
$ sudo iptables -t nat -L DOCKER -n -v
Chain DOCKER (2 references)
pkts bytes target prot opt in out source destination
0 0 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080 to:172.17.0.2:80
!docker0: matches traffic arriving from outside thedocker0bridge (such aseth0).tcp dpt:8080: matches packets targeting TCP port8080.to:172.17.0.2:80: rewrites the destination and forwards the packet in kernel space.
2) What docker-proxy is doing
If kernel DNAT handles most traffic, why does ps aux | grep docker-proxy show a separate process for every published port?
1
root 12480 0.0 0.1 ... /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8080 -container-ip 172.17.0.2 -container-port 80
docker-proxy is a user-space fallback relay. It covers cases where kernel DNAT doesn’t apply cleanly, such as host-local loopback traffic (localhost:8080) without hairpin NAT or certain IPv6 proxy paths.
3. --network host: bare-metal speed vs. broken isolation
Standard bridge networking sends every packet through docker0 (or a custom bridge), a veth pair, iptables DNAT, and checksum updates. For high-throughput API gateways, WebRTC media servers, or latency-sensitive caches pushing hundreds of thousands of packets per second, that extra path can raise CPU usage and tail latency.
That’s where --network host comes in.
flowchart TD
subgraph BridgeMode ["Bridge Mode (-p 8080:80)"]
B_Host["Host Network Stack (eth0)"] --> B_Bridge["Bridge + iptables DNAT"]
B_Bridge --> B_Veth["veth pair isolation"]
B_Veth --> B_Cont["Container Network Stack (eth0: 172.17.0.2)"]
end
subgraph HostMode ["Host Mode (--network host)"]
H_Host["Host Network Stack (eth0, lo, iptables)"] -->|"Zero NAT overhead"| H_Cont["Container Process (shared netns)"]
end
How host mode works
With --network host, Docker skips creating a separate network namespace altogether. The container shares the host’s network stack directly:
- Calling
bind(8080)inside the container binds port8080directly on the host. -pflags are unnecessary and ignored.- Removing
vethpairs and DNAT gives you native host network I/O performance.
Three reasons to avoid --network host by default
Host networking removes the network isolation boundary that containers rely on. Don’t enable it unless you’ve measured a real bridge/NAT bottleneck.
- Port collisions: Because there’s no isolated namespace, you can’t run two containers listening on port
8080on the same host—which breaks simple blue-green or rolling deployments on a single machine. - Weakened security boundary: A process inside the container can reach the host’s
127.0.0.1services and every host interface. If an attacker gets RCE inside the container, local admin ports and host databases are wide open. - Broken behavior on macOS and Windows: Docker Desktop runs containers inside a Linux VM. Passing
--network hostbinds to the VM’s network stack, not your Mac or Windows host, solocalhost:8080in your browser won’t reach the container unless you enable host networking beta features.
4. How 0.0.0.0 port binding bypasses UFW
One of the most common Docker security incidents happens on Linux VPS hosts: you configure UFW (ufw deny 5432) assuming your PostgreSQL or Redis container is firewalled, yet public internet scanners connect right into it.
-p 8080:80 defaults to 0.0.0.0
Writing -p 8080:80 is shorthand for binding on every interface, including your public NIC:
1
docker run -d -p 0.0.0.0:8080:80 nginx:alpine
Even worse, Docker’s iptables rules run before UFW’s INPUT chain:
1
2
3
4
5
6
7
8
9
10
11
[Incoming Packet from Internet]
│
▼
iptables PREROUTING
│
▼
iptables DOCKER chain (DNAT rewrites destination -> routes to FORWARD)
│
├─► FORWARD chain (packet reaches the container!)
│
└─► INPUT chain (where UFW rules live — never evaluated!)
UFW places its deny rules in the INPUT chain, which only inspects packets destined for the host itself. Because Docker’s PREROUTING DNAT rule rewrites the destination to the container IP, the packet jumps straight to FORWARD and bypasses UFW completely. That’s how unauthenticated Redis (6379) and PostgreSQL (5432) containers end up compromised within hours of deployment.
The fix: bind to 127.0.0.1 (or don’t publish at all)
If a container only needs to be reached by a host reverse proxy (Nginx, Caddy, Envoy) or local debugging tools, bind it explicitly to loopback:
1
2
# Reachable only from localhost on the host machine
docker run -d -p 127.0.0.1:8080:8080 --name payment-api my-api:latest
Apply the same discipline in compose.yaml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
services:
# Only the reverse proxy publishes public ports
reverse-proxy:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
depends_on:
- internal-api
# Backend API bound to loopback for local host access only
internal-api:
image: my-internal-api:latest
ports:
- "127.0.0.1:8080:8080"
# Internal Redis needs no host port mapping at all
internal-redis:
image: redis:7-alpine
expose:
- "6379"
Databases and caches that only talk to other containers don’t need
ports:at all. Keep them on a shared user-defined bridge and connect by container name, as I covered in Docker bridge networks and embedded DNS service discovery.
5. Comparison table and pre-deploy checklist
Choose your port exposure strategy based on who actually needs to reach the container:
| Method | Example | Mechanism | Best fit | Main risk |
|---|---|---|---|---|
EXPOSE | EXPOSE 8080 | Image metadata only | Documentation and -P hints | Doesn’t open any port |
Default -p | -p 8080:8080 | 0.0.0.0 iptables DNAT | Public entrypoints (Nginx, Caddy) | Bypasses UFW on public hosts |
Loopback -p | -p 127.0.0.1:8080:8080 | 127.0.0.1 iptables DNAT | APIs behind a host proxy, local dev DBs | Not reachable from other hosts |
| Host network | --network host | Shared host netns | High-PPS proxies, WebRTC media servers | Port collisions, no network isolation, VM quirks on Mac |
Run this quick check before deploying to any internet-facing server:
- Don’t rely on
EXPOSEto publish traffic: Declare explicitports:incompose.yamlor-pindocker runfor entrypoints. - Audit
0.0.0.0bindings on the host: Runss -tulpn | grep LISTENand confirm no database (5432,3306,6379) is listening on0.0.0.0unless you intentionally exposed it behind a cloud security group. - Justify
--network hostwith measurements: If you’re using host mode just to skip port mapping, switch back to a user-defined bridge network.