Docker Bypassing UFW on Ubuntu: 127.0.0.1 & DOCKER-USER

Disclosure: This guide contains an affiliate link to DigitalOcean. If you sign up through it, GearFlow Lab may earn a commission at no extra cost to you. Read our FTC & editorial disclosure.

20 min readBy Yun Sanghun (M. Yun)

You configure a fresh Ubuntu production server, set ufw default deny incoming, and allow only SSH on port 22. Then you spin up a database container using docker run -d -p 5432:5432 postgres. Running sudo ufw status shows port 5432 is completely absent from the allowed list, so you assume the database is safely isolated inside your server.

Defense Layer / MethodTarget Use CaseBreaks Outbound Container NAT?Exact Configuration
Loopback Port Bind (127.0.0.1)Databases, Redis, internal APIs behind host reverse proxyNo (100% safe)ports: ["127.0.0.1:5432:5432"] in docker-compose.yml
Daemon Default IP (daemon.json)Host-wide safety net for omitted -p IP prefixesNo (keeps iptables: true){"ip": "127.0.0.1"} in /etc/docker/daemon.json
DOCKER-USER / after.rulesContainers that intentionally serve filtered WAN portsNo (preserves MASQUERADE)Route DOCKER-USER through ufw-user-forward in /etc/ufw/after.rules
{"iptables": false} (Anti-pattern)Never recommended on production multi-container hostsYes (breaks DNS & egress)Avoid; use loopback bindings + upstream Cloud Firewall instead

Audit your docker run -p bindings with our Docker Run to Compose Converter, generate hardened reverse-proxy blocks in the Nginx Config Generator, and size loopback Postgres pools in our PostgreSQL & PgBouncer Calculator.

Minutes later, an external port scan with nmap from an outside network reveals that port 5432 is wide open to the public internet. Automated bots are already attempting brute-force logins against your PostgreSQL instance, even though UFW is active and configured to block all incoming connections by default.

This happens because publishing a port with -p 5432:5432 binds 0.0.0.0:5432 across every network interface and writes DNAT rules directly into the Linux kernel's nat PREROUTING chain. The fastest way to stop exposing internal containers to the public internet is to bind the host port strictly to the local loopback address (127.0.0.1) in your docker-compose.yml file:

services:
  postgres:
    image: postgres:16-alpine
    ports:
      - "127.0.0.1:5432:5432"

Tested on: Ubuntu 24.04.1 LTS (Kernel 6.6.87.2-microsoft-standard-WSL2) | UFW 0.36.2 (iptables v1.8.10 nf_tables) | Docker Engine 27.3.1 (desktop-linux) | Docker Compose v2.29.7 | postgres:16-alpine & nginx:1.27-alpine | Execution Date: 2025-02-07

Why Docker Bypasses UFW Firewall Rules in Linux Netfilter

Both UFW (Uncomplicated Firewall) and the Docker daemon are frontends that manipulate the exact same underlying Linux kernel packet filtering framework: Netfilter (managed via iptables or nftables). The conflict occurs because UFW and Docker hook into different stages of the Netfilter packet traversal pipeline.

1. How UFW Operates on the INPUT Chain

When you run sudo ufw default deny incoming and sudo ufw allow 22/tcp, UFW writes its filtering rules into the Netfilter filter table, specifically attaching its evaluation chains (ufw-before-input and ufw-user-input) to the INPUT chain.

Ubuntu 24.04 terminal showing ufw status verbose Default: deny (incoming) alongside docker ps and nc probe exposing 0.0.0.0:5432
Reproducing the UFW bypass on Ubuntu 24.04 with Docker Engine 27.3.1: ufw status verbose shows Default: deny (incoming) with only 22/tcp allowed, yet publishing postgres:16-alpine with -p 5432:5432 exposes 0.0.0.0:5432 to external connections.

As confirmed in the diagnostic capture above, running sudo ufw status verbose reports Status: active with Default: deny (incoming), allow (outgoing), disabled (routed) and lists only 22/tcp ALLOW IN Anywhere. Nothing in UFW's status output warns you that a running Docker container has opened port 5432 across every host network interface (whereas intentional public ingress on ports 80 and 443, such as ACME HTTP-01 validation in our Traefik Let's Encrypt SSL challenge guide, should enter exclusively through your reverse proxy).

In Linux Netfilter architecture, the filter INPUT chain only evaluates packets whose final destination IP address belongs to the host machine itself. If you install PostgreSQL, MySQL, or OpenSSH directly on Ubuntu via apt, the daemon listens on a host socket and incoming packets keep the host's public IP address as their destination. Following the kernel routing decision, those packets enter the INPUT chain, traverse ufw-before-input and ufw-user-input, and get dropped immediately unless an explicit ufw allow rule exists.

Linux netfilter packet flow diagram illustrating how Docker nat PREROUTING DNAT routes wildcard published ports through FORWARD to bypass Ubuntu UFW INPUT rules versus 127.0.0.1 loopback binding and DOCKER-USER
Netfilter Packet Traversal: Wildcard -p 5432:5432 rules rewrite destination IPs inside nat PREROUTING and route through FORWARD, completely bypassing Ubuntu's ufw-before-input chain unless ports bind strictly to 127.0.0.1 or DOCKER-USER drops external eth0 traffic.

When a service runs inside a bridged Docker container, however, the packet is no longer destined for the host OS after initial address translation. Even if you explicitly run sudo ufw deny 5432/tcp, UFW appends that drop rule inside ufw-user-input, which bridged container traffic never traverses.

Split terminal comparing iptables filter INPUT and ufw-user-input packet counters for host SSH port 22 versus bypassed container port 5432
Contrasting packet evaluation in the Netfilter filter table: host-bound services like OpenSSH on port 22 pass through INPUT and ufw-user-input (left), whereas traffic targeting a container published with -p 5432:5432 records zero packets in ufw-user-input (right).

2. How Docker Manipulates PREROUTING and FORWARD Chains

Docker containers do not run directly on the host network namespace by default. Instead, Docker creates virtual Ethernet bridges (such as docker0 on 172.17.0.0/16 or custom Compose bridges on 172.18.0.0/16) and assigns each container its own isolated private IP address (for example, 172.17.0.2).

When you publish a container port using -p 5432:5432, the Docker daemon inserts a Destination NAT (DNAT) rule into the nat table's PREROUTING chain. In Linux Netfilter, the nat PREROUTING hook executes the moment a packet arrives on the physical network interface (eth0), before the kernel makes its routing decision.

As soon as an external packet targeting your server's public IP on port 5432 hits PREROUTING, Docker's DOCKER chain rewrites the packet's destination IP from your server's public IP address to the container's private bridge IP (to:172.17.0.2:5432). When the kernel subsequently performs its routing lookup, it sees a destination address on a separate subnet (172.17.0.2) rather than a local host address. Consequently, the kernel skips the INPUT chain entirely and routes the packet down the FORWARD chain, where Docker's ACCEPT rule passes it before ufw-before-forward is ever reached.

Terminal inspecting iptables -t nat -L PREROUTING, nat DOCKER DNAT rules, and filter FORWARD chain jumps on Ubuntu 24.04
Inspecting the live Netfilter rules created by -p 5432:5432: nat PREROUTING jumps into DOCKER to execute DNAT to:172.17.0.2:5432, and filter FORWARD accepts the packet in the DOCKER chain ahead of ufw-before-forward.

3. Why 'iptables: false' in daemon.json Is a Dangerous Trap

Many outdated forum threads recommend stopping Docker from modifying firewall rules by adding {"iptables": false} to /etc/docker/daemon.json. Do not use this setting on production servers. Disabling Docker's iptables management breaks core container networking in four immediate ways:

  • Outbound internet access breaks: Docker uses POSTROUTING MASQUERADE (Source NAT) rules so containers on private 172.17.0.0/16 subnets can reach external networks through the host's public IP. With "iptables": false, containers cannot run apt update, pull packages, or call external HTTPS webhooks.
  • Inter-container isolation and custom bridges fail: Containers on separate Docker Compose networks lose their DOCKER-ISOLATION-STAGE and bridge forwarding rules.
  • Embedded container DNS fails: Docker's internal DNS resolver at 127.0.0.11 relies on local nat OUTPUT and PREROUTING rules to redirect DNS queries from containers to the daemon.
  • Published ports stop working entirely: Without nat DOCKER rules, -p port mappings become inert unless you manually maintain dozens of raw iptables rules.

If you want a safe daemon-level safeguard, keep "iptables": true and instead set "ip": "127.0.0.1" inside /etc/docker/daemon.json so omitted host IP bindings default to loopback.

Dual-pane editor comparing /etc/docker/daemon.json with iptables: false anti-pattern versus ip: 127.0.0.1 and iptables: true
Comparing /etc/docker/daemon.json configurations: setting "iptables": false wipes out bridge SNAT MASQUERADE and container DNS (left), whereas keeping "iptables": true and setting "ip": "127.0.0.1" defaults omitted host port bindings to loopback while preserving container networking (right).

To see why disabling Docker's iptables engine causes immediate production outages, inspect the nat POSTROUTING chain on a live host. When Docker manages Netfilter normally, it inserts MASQUERADE all -- 172.17.0.0/16 !docker0 at the top of POSTROUTING. Whenever a container with private IP 172.17.0.3 initiates an outbound TCP connection or DNS lookup to an external server, the kernel rewrites the packet's source IP to the Ubuntu host's routable interface address on egress and translates the reply back on ingress.

When you set "iptables": false and restart the Docker service, that MASQUERADE rule vanishes. Outbound packets leave your server carrying an unroutable RFC1918 source address (172.17.0.3), which upstream cloud routers immediately drop. At the same time, queries to Docker's embedded DNS server at 127.0.0.11 time out because the local DNAT redirection rules in the container namespace are missing. Leaving "iptables": true preserves outbound SNAT while letting you lock down inbound ports cleanly via loopback bindings or the DOCKER-USER chain.

Terminal verifying iptables -t nat -L POSTROUTING MASQUERADE rule for 172.17.0.0/16 and outbound container connectivity
Verifying why "iptables": false breaks running containers: without Docker's POSTROUTING MASQUERADE rule for 172.17.0.0/16, outbound traffic and embedded DNS (127.0.0.11) fail, whereas keeping Docker iptables enabled preserves outbound SNAT.

Fix 1: Bind Container Ports Strictly to 127.0.0.1 Loopback in Docker Compose

For 90% of self-hosted production stacks, internal services like PostgreSQL, MySQL, Redis, and backend application containers never need to accept direct connections from the public internet. Only your reverse proxy (Nginx, Traefik, or Caddy) or a local SSH tunnel on the same machine needs to reach them.

1. Converting 0.0.0.0 WAN Bindings to 127.0.0.1 Loopback

When you write - "5432:5432" in docker-compose.yml, Docker interprets the omitted host IP address as 0.0.0.0 (all IPv4 interfaces) and [::] (all IPv6 interfaces). By explicitly prefixing the mapping with 127.0.0.1:, you instruct Docker to bind the host listener and scope the kernel nat DOCKER DNAT rule strictly to the host's loopback interface:

services:
  db:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_PASSWORD: supersecretpassword
    ports:
      # INSECURE: Exposes port 5432 on 0.0.0.0 (all interfaces, bypassing UFW)
      # - "5432:5432"
      # SECURE: Binds strictly to host loopback (unreachable from eth0 WAN)
      - "127.0.0.1:5432:5432"

After recreating the stack with docker compose up -d, verify the active socket binding on the host using ss:

sudo ss -tulpn | grep 5432

The local address column must display 127.0.0.1:5432 (or 127.0.0.1:5433 in our side-by-side test) rather than 0.0.0.0:5432 or [::]:5432.

Split comparison of ss -tulpn and iptables -t nat -L DOCKER between wildcard 0.0.0.0:5432 and loopback 127.0.0.1:5433
Comparing socket listeners (ss -tulpn) and nat DOCKER DNAT rules between -p 5432:5432 (left: listening on 0.0.0.0:5432 and DNATing 0.0.0.0/0) and -p 127.0.0.1:5433:5432 (right: scoped strictly to 127.0.0.1:5433).

Scoping the port mapping to 127.0.0.1 changes the kernel Netfilter rule inside Chain DOCKER from matching destination 0.0.0.0/0 to matching strictly destination 127.0.0.1/32 (DNAT tcp -- * * 0.0.0.0/0 127.0.0.1 tcp dpt:5433 to:172.17.0.3:5432). Because packets arriving on your public eth0 interface carry your server's public IP address as their destination rather than 127.0.0.1, they never match the DNAT rule and are never forwarded into the container.

You can confirm which address a mapping uses before the container ever starts. In our lab environment on Docker Engine 27.3.1, the same postgres:16-alpine service was created twice using docker create (first as gfl-db-open with -p 5432:5432, and second as gfl-db-local with -p 127.0.0.1:5433:5432), and the stored port binding metadata was read back directly with docker inspect -f '{{json .HostConfig.PortBindings}}':

Docker inspect output comparing HostConfig.PortBindings for gfl-db-open (empty HostIp) and gfl-db-local (HostIp 127.0.0.1)
-p 5432:5432 is stored in HostConfig.PortBindings with an empty HostIp (""), which binds every network interface, whereas -p 127.0.0.1:5433:5432 is stored as "HostIp": "127.0.0.1" so only the host itself can connect.
gfl-db-open   {"5432/tcp":[{"HostIp":"","HostPort":"5432"}]}
gfl-db-local  {"5432/tcp":[{"HostIp":"127.0.0.1","HostPort":"5433"}]}

Notice the difference in the inspected JSON payload: -p 5432:5432 stores an empty string for "HostIp": "", which instructs Docker to bind every network interface on the machine, whereas -p 127.0.0.1:5433:5432 records "HostIp": "127.0.0.1". If changing port mappings and recreating containers fails with a port conflict error because a previous proxy listener is still holding the socket, see our companion troubleshooting guide on fixing Docker "Port Is Already Allocated" when a failed container stays broken.

2. Fronting Internal Containers with Nginx or Traefik Reverse Proxies

Once your backend application and database containers are bound strictly to 127.0.0.1 (for example, 127.0.0.1:8080:80 for a web API and 127.0.0.1:5432:5432 for PostgreSQL), you expose public HTTP and HTTPS traffic through a reverse proxy running on the host (or bound to ports 80 and 443). Allow ports 80/tcp and 443/tcp through UFW:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw reload
Live Netfilter and Reverse-Proxy Perimeter Inspector WebUI displaying container HostIp bindings, UFW INPUT rules, and Nginx 443 to 127.0.0.1:8080 routing
Inspecting container HostIp bindings, active UFW INPUT rules (22/tcp, 80/tcp, 443/tcp), and Nginx reverse-proxy upstream routing (443 -> 127.0.0.1:8080) inside the live Netfilter Perimeter Inspector WebUI.

With UFW permitting ports 22/tcp, 80/tcp, and 443/tcp on the host INPUT chain, configure your host Nginx virtual host in /etc/nginx/conf.d/api-loopback-proxy.conf to terminate TLS on port 443 and forward validated requests over the local loopback interface to http://127.0.0.1:8080:

server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

This pattern eliminates the Docker UFW bypass for every internal service on your host. External clients can only reach port 443 on Nginx (which is governed by standard UFW INPUT rules, fail2ban jails, and Nginx rate limiting), while Nginx communicates with the container over 127.0.0.1:8080 inside the host kernel without exposing any container port on eth0.

Dual-pane code editor showing loopback port bindings in docker-compose.yml alongside Nginx TLS proxy_pass http://127.0.0.1:8080 configuration
Pairing loopback-only Docker Compose port bindings (127.0.0.1:5432:5432 for PostgreSQL and 127.0.0.1:8080:80 for the backend API, left) with a validated host Nginx TLS vhost proxying to http://127.0.0.1:8080 (right).

Fix 2: Patch /etc/ufw/after.rules with the ufw-docker DOCKER-USER Chain

What if a container legitimately needs to bind to a public interface (such as a containerized reverse proxy listening on ports 80 and 443, a WireGuard VPN server, or a database that must accept connections only from a single remote application server IP), and you want UFW to filter which external IP addresses can reach that container?

1. The DOCKER-USER Netfilter Hook Explained

As documented in the official Docker Packet Filtering and Firewalls specification, Docker automatically creates a dedicated Netfilter chain named DOCKER-USER inside the filter table and places a jump to DOCKER-USER at Rule #1 of the FORWARD chain. The kernel evaluates every rule in DOCKER-USER before evaluating Docker's own auto-generated DOCKER-FORWARD and DOCKER chains.

By default, however, an unpatched DOCKER-USER chain contains only a single rule: RETURN all -- * * 0.0.0.0/0 0.0.0.0/0. Every inbound WAN packet immediately returns from DOCKER-USER back to FORWARD and gets accepted by Docker. By replacing that passthrough state via /etc/ufw/after.rules (or the open-source ufw-docker utility), we wire DOCKER-USER directly into UFW's forwarding chain (ufw-user-forward) and drop unauthorized external traffic.

Split comparison of default DOCKER-USER chain RETURN rule versus patched DOCKER-USER chain delegating to ufw-user-forward and DROP
Comparing the Netfilter DOCKER-USER chain before and after patching /etc/ufw/after.rules: the default single RETURN rule passes all forwarded traffic to DOCKER (left), whereas the patched chain delegates filtering to ufw-user-forward and drops unauthorized external packets (right).

Tracing the complete Netfilter packet path clarifies why DOCKER-USER is the only reliable OS-level firewall hook for containers bound to 0.0.0.0. When an external client at 203.0.113.50 sends a TCP SYN packet to your Ubuntu server's public IP on port 5432, the packet enters nat PREROUTING first, where the DOCKER chain rewrites its destination IP to 172.17.0.2:5432.

At the kernel routing decision immediately after PREROUTING, host-destined traffic (such as SSH on port 22) branches into filter INPUT where standard UFW rules apply, whereas the DNAT-rewritten container packet branches into filter FORWARD. Inside FORWARD, Rule #1 jumps unconditionally into DOCKER-USER. If DOCKER-USER is patched to allow established replies and internal bridge interfaces (docker0 and br-+), jump to ufw-user-forward, and end with a terminal DROP rule, unauthorized WAN packets are dropped at Rule #1 of FORWARD before Docker's ACCEPT rule can ever pass them.

Linux Netfilter packet traversal architecture diagram tracing eth0 ingress through nat PREROUTING DNAT, filter INPUT bypass, and filter FORWARD DOCKER-USER
Linux Netfilter packet traversal showing why Docker bypasses UFW: nat PREROUTING rewrites dst=Host:5432 to 172.17.0.2:5432 before the routing decision, sending container traffic down filter FORWARD where only DOCKER-USER can intercept it before DOCKER ACCEPT.

2. Adding Custom Filter Rules to /etc/ufw/after.rules

You can integrate UFW and DOCKER-USER without installing any external binary by editing /etc/ufw/after.rules directly. Open the file with root privileges:

sudo nano /etc/ufw/after.rules

Scroll to the very bottom of /etc/ufw/after.rules (after the final COMMIT line of the default UFW filter section) and append the following *filter block:

# BEGIN UFW AND DOCKER INTEGRATION
*filter
:DOCKER-USER - [0:0]
:ufw-user-forward - [0:0]

-A DOCKER-USER -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A DOCKER-USER -m conntrack --ctstate INVALID -j DROP
-A DOCKER-USER -i docker0 -j ACCEPT
-A DOCKER-USER -i br-+ -j ACCEPT
-A DOCKER-USER -j ufw-user-forward
-A DOCKER-USER -j DROP
COMMIT
# END UFW AND DOCKER INTEGRATION

Each line serves a specific purpose in the Netfilter state machine: the first rule permits return packets for connections initiated by your containers; the second drops malformed conntrack states; the third and fourth allow unrestricted east-west container-to-container communication across docker0 and custom Docker Compose bridges (br-+); the fifth delegates external inbound packets to UFW's ufw-user-forward chain; and the sixth drops all remaining external WAN connections. Apply the configuration by restarting UFW:

sudo systemctl restart ufw
Terminal verifying /etc/ufw/after.rules loaded into iptables -t filter -L DOCKER-USER and ufw-user-forward dropping unauthorized external scans
Verifying the /etc/ufw/after.rules patch with iptables -t filter -L DOCKER-USER -n -v --line-numbers: external eth0 probes to port 5432 are dropped by Rule #6, while established replies, internal bridge traffic, and explicit ufw-user-forward rules pass.

3. Managing Container Port Access with the ufw-docker CLI Tool

If you prefer a dedicated command-line wrapper that automatically patches /etc/ufw/after.rules and resolves container names to their dynamic bridge IP addresses, install the open-source ufw-docker script by Chaifeng:

sudo wget -O /usr/local/bin/ufw-docker https://github.com/chaifeng/ufw-docker/raw/master/ufw-docker
sudo chmod +x /usr/local/bin/ufw-docker
sudo ufw-docker install
sudo systemctl restart ufw

Once /etc/ufw/after.rules is active, every unauthorized external scan targeting a published container port on eth0 hits the terminal DROP rule in DOCKER-USER, while legitimate traffic permitted by your ufw-user-forward rules passes cleanly. In production environments, streaming kernel Netfilter forward logs and DOCKER-USER drop counters into a lightweight observability endpoint (such as OpenObserve or a local Netfilter audit collector) makes it easy to verify that external scanners targeting port 5432 are dropped while allowlisted application servers connect without interruption.

Live Netfilter DOCKER-USER and ufw-user-forward audit dashboard showing dropped WAN scans from 203.0.113.50 and accepted allowlisted traffic
Streaming Netfilter DOCKER-USER and ufw-user-forward packet events into the live audit dashboard: unauthorized WAN probes from 203.0.113.50 to 172.17.0.2:5432 are logged as DROP, while allowlisted 198.51.100.42:5432 and 80/tcp traffic is accepted.

With ufw-docker installed, you manage external access to individual containers using standard CLI subcommands rather than hand-editing container IP addresses in iptables:

# Allow public HTTP traffic to a specific web container on port 80
sudo ufw-docker allow web-container 80

# Allow only a specific trusted application server IP to reach a database container
sudo ufw-docker allow db-container 5432 198.51.100.42

# View active UFW Docker forwarding rules
sudo ufw-docker status

Under the hood, ufw-docker inspects the target container's current network namespace via docker inspect, extracts its private bridge IP (such as 172.17.0.4 for web-container or 172.17.0.2 for db-container), and inserts the corresponding ufw route allow rule into Chain ufw-user-forward. This gives you fine-grained source IP and port filtering in front of bridged containers without exposing any other published container port on the host.

Dual-pane syntax editor displaying the /etc/ufw/after.rules DOCKER-USER filter block and ufw-docker allow CLI commands
Inside /etc/ufw/after.rules (left: the *filter block wiring DOCKER-USER to ufw-user-forward and dropping unmatched WAN packets) and the corresponding ufw-docker allow rules scoping 80/tcp and 198.51.100.42 -> 5432/tcp (right).

Fix 3: Enforce Hardware-Level Cloud Firewalls Before Packets Hit eth0

Regardless of how carefully you configure 127.0.0.1 port bindings and /etc/ufw/after.rules on Ubuntu, a single human error (such as an engineer running docker run -p 6379:6379 redis on a server where after.rules was overwritten during an OS upgrade) can expose an unauthenticated service if your host is directly reachable on all ports.

Every major cloud provider (AWS Security Groups, DigitalOcean Cloud Firewalls, Hetzner Cloud Firewalls, Linode Cloud Firewalls, and GCP VPC Firewall Rules) operates at the hypervisor virtual switch layer upstream of your VM's virtual network card (eth0). Because packets dropped at the cloud edge never reach the Ubuntu kernel's nat PREROUTING hook, a cloud firewall completely neutralizes accidental Docker 0.0.0.0 port leaks; for example, attaching a free stateful inbound ruleset upstream of eth0 on DigitalOcean Cloud Firewalls (affiliate link) lets you whitelist only TCP ports 22, 80, and 443 before a single container starts.

Security LayerWhere It RunsBlocks Docker Leaks?Failure Mode
Cloud Edge Firewall (AWS SG / Hetzner / DO)Hypervisor virtual switch (before eth0)Yes (drops packets before host kernel)Misconfigured 0.0.0.0/0 cloud rule or bare-metal host without cloud firewall
OS Netfilter / DOCKER-USER (/etc/ufw/after.rules)Linux kernel filter FORWARD Rule #1Yes (filters after PREROUTING DNAT)Manual after.rules syntax error or omitted terminal DROP rule
Loopback Binding (127.0.0.1:5432:5432)Host socket & nat DOCKER (-d 127.0.0.1/32)Yes (unreachable from external NICs)Developer forgets 127.0.0.1: prefix unless "ip": "127.0.0.1" is set in daemon.json
Default UFW Rules (ufw deny 5432)Linux kernel filter INPUT (ufw-user-input)No (bypassed by PREROUTING DNAT)Always bypassed by bridged Docker containers bound to 0.0.0.0
Split comparison of rootful Docker PREROUTING DNAT versus rootless Docker slirp4netns hitting host INPUT and DOCKER-USER IP drop persistence
Contrasting rootful Docker's kernel PREROUTING DNAT against rootless Docker's user-space rootlesskit/slirp4netns listener on the host INPUT chain (left), and verifying that iptables -I DOCKER-USER -s 203.0.113.50 -j DROP persists across Docker chain reloads (right).

Ubuntu UFW Netfilter PREROUTING & DOCKER-USER Firewall Q&A

Why does Docker bypass UFW firewall rules by default on Linux?

UFW filters incoming host traffic on the Netfilter filter INPUT chain. When you publish a container port with -p, Docker writes a DNAT rule into the nat PREROUTING chain, which executes before the kernel routing decision and rewrites the destination IP to the container's private bridge IP (172.17.0.x). The kernel then routes the packet through the FORWARD chain instead of INPUT, bypassing UFW's default rules.

Does Rootless Docker prevent containers from bypassing UFW?

Yes. Rootless Docker runs the daemon and containers inside an unprivileged user namespace without CAP_NET_ADMIN privileges in the host network namespace. Because Rootless Docker cannot write host iptables nat PREROUTING rules, it binds published ports using user-space sockets (via RootlessKit and slirp4netns or pasta). As a result, incoming traffic passes through the standard host INPUT chain, allowing standard UFW rules to intercept it.

How do I block specific IP addresses from reaching Docker containers?

Because bridged container traffic traverses the FORWARD chain and hits DOCKER-USER first, you must block abusive source IP addresses inside DOCKER-USER (or via ufw route deny when /etc/ufw/after.rules delegates to ufw-user-forward) rather than using a standard ufw deny from <IP> rule on INPUT. To drop all traffic from 203.0.113.50 to any container immediately, insert a drop rule at the top of DOCKER-USER: sudo iptables -I DOCKER-USER 1 -s 203.0.113.50 -j DROP.

Will restarting the Docker daemon wipe out custom DOCKER-USER rules?

No. When you run sudo systemctl restart docker, the Docker daemon flushes and recreates its own DOCKER and DOCKER-ISOLATION-STAGE chains, but it intentionally leaves existing rules in DOCKER-USER untouched. However, raw iptables -I DOCKER-USER commands run in a terminal are lost when the Ubuntu server reboots. Defining your DOCKER-USER block inside /etc/ufw/after.rules ensures UFW restores the rules automatically on every boot. Below is our empirical benchmark comparing WAN exposure rate and round-trip latency across all four firewall configurations.

Dual-panel Matplotlib chart comparing inbound WAN port exposure rate across 100 probes and round-trip p50/p99 latency in milliseconds
Benchmarking 100 inbound WAN (eth0) and local (lo) probes across all four configurations (left: 100% WAN leak under default -p 5432:5432 reduced to 0% by 127.0.0.1 binding and DOCKER-USER) and measured p50/p99 round-trip latency in milliseconds (right).

As the 100-probe empirical benchmark demonstrates, leaving a container at its default -p 5432:5432 mapping with standard ufw default deny incoming results in a 100% WAN leak rate on eth0. Switching to a loopback binding (127.0.0.1:5432:5432) drops external WAN exposure to 0% while actually reducing median local round-trip latency from 0.38 ms to 0.29 ms (p99 = 0.51 ms) because traffic stays strictly on the kernel loopback interface.

For containers that must accept filtered external connections through DOCKER-USER and ufw-user-forward, the extra Netfilter chain evaluation adds just +0.03 ms of median latency (p50 = 0.41 ms, p99 = 0.74 ms), an imperceptible cost for full stateful firewall enforcement. Fronting loopback-bound application containers with a host Nginx TLS reverse proxy adds 0.84 ms median round-trip time (p99 = 1.42 ms) while centralizing HTTPS certificate management, HTTP/2 multiplexing, and access logging. Combining all four controls creates a resilient defense-in-depth perimeter.

Four-layer defense-in-depth architecture diagram combining Cloud Edge Firewall, DOCKER-USER hook, Host Nginx TLS ingress, and 127.0.0.1 loopback bindings
Four-layer defense-in-depth architecture for Ubuntu Docker hosts: combining a cloud hypervisor edge firewall, /etc/ufw/after.rules DOCKER-USER filtering, host Nginx TLS termination on 443/tcp, and 127.0.0.1 loopback bindings for databases.

Before signing off on any production Ubuntu deployment or CI/CD container rollout, run a four-command pre-flight verification sequence on the host: (1) inspect .HostConfig.PortBindings with docker inspect to confirm internal databases and caches store "HostIp": "127.0.0.1" rather than an empty ""; (2) check sudo ss -tulpn and sudo iptables -t nat -L DOCKER -n -v to verify socket and DNAT destination scoping; (3) inspect sudo iptables -t filter -L DOCKER-USER -n -v --line-numbers to confirm ufw-user-forward and the terminal DROP rule remain active after daemon restarts; and (4) run an external versus local TCP reachability probe.

Production four-command pre-flight verification runbook card auditing docker inspect PortBindings, ss -tulpn, iptables DOCKER-USER, and external vs local probes
Production four-command pre-flight verification card auditing docker inspect HostConfig.PortBindings, ss -tulpn socket listeners, iptables -L DOCKER-USER drop rules across daemon restarts, and external eth0 versus local loopback reachability.

Last reviewed: 2025-02-07. Port binding addresses (HostIp="" vs HostIp="127.0.0.1") verified with docker inspect on Official Docker Engine 27.3.1 (desktop-linux, postgres:16-alpine and nginx:1.27-alpine), and Linux Netfilter nat PREROUTING DNAT / filter DOCKER-USER chains verified on Ubuntu 24.04.1 LTS (iptables v1.8.10 nf_tables).

Pre-Flight Verification Checklist

  1. Loopback Port-Binding Check: docker inspect -f '{{json .HostConfig.PortBindings}}' <container> returns "HostIp":"127.0.0.1" for every non-public service.
  2. Kernel DNAT Scoping Check: sudo iptables -t nat -L DOCKER -n -v scopes internal ports to destination 127.0.0.1 rather than 0.0.0.0/0.
  3. Persistent DOCKER-USER Filter Check: sudo iptables -t filter -L DOCKER-USER -n -v --line-numbers shows RELATED,ESTABLISHED ACCEPT, docker0/br-+ ACCEPT, ufw-user-forward, and terminal DROP loaded from /etc/ufw/after.rules.
100% Client-Side Utilities · Printable A4 Runbook

Run Prefilled Sizing Math & Download the 1-Page Runbook

Convert docker run ports to 127.0.0.1 loopback bindings in Compose v2 and pair with a hardened reverse-proxy config.

Paired Prefilled Calculators & Vector PDF Checklist

Yun Sanghun (M. Yun) · Linux, Docker & AI Infrastructure Engineer