Security

Docker ignores your UFW firewall. Here is how to fix it

A port published with Docker answers from the internet even when ufw denies it. We reproduced it on Ubuntu 24.04 with Docker 29 and tested the fixes Docker documents: 127.0.0.1, the provider's firewall and DOCKER-USER.

TL;DR

  • Docker (opens in a new tab) publishes a port by rewriting the packet's address in the nat table before ufw's INPUT rules run, so ufw never sees traffic to a published container port.
  • Publish only your reverse proxy's 80 and 443, and bind everything else to 127.0.0.1 ("127.0.0.1:3000:3000" in Compose) or publish nothing and let the proxy reach the app over the Compose network.
  • Put the provider's firewall (Hetzner (opens in a new tab), DigitalOcean (opens in a new tab)) in front of the server: it is outside the server, so nothing Docker does can open a hole in it.
  • For rules that must live on the server, use Docker's DOCKER-USER chain, loaded at boot before Docker starts, and don't set "iptables": false.
On this page

Docker ignores ufw because it publishes container ports with its own iptables rules, which redirect the traffic to the container before ufw's rules are ever checked. ufw status can say "deny incoming" while docker run -p 8080:80 answers the whole internet on port 8080. Docker's documentation says it plainly: "Docker and ufw use firewall rules in ways that make them incompatible with each other." The fixes are also Docker's: publish internal services only on 127.0.0.1 (or not at all), put the provider's firewall in front of the server, and write rules that must live on the server into Docker's DOCKER-USER chain.

This article is part of our checklist for hardening an Ubuntu 24.04 server. We reproduced the problem and tested each fix on 11 November 2026: Ubuntu 24.04.5 running systemd in a privileged container, with Docker Engine 29.9.3 from Docker's apt repository, ufw 0.36.2, and a second container on the same network as the outside visitor. A cloud server applies the same firewall rules, but we didn't test on one.

See the problem in two minutes

We set ufw up in the usual way: deny everything incoming, allow SSH.

sudo ufw default deny incoming
sudo ufw allow OpenSSH
sudo ufw enable

Then we started two things on the server: nginx (opens in a new tab) in a container published on port 8080, and a plain Python web server on port 8081, outside Docker.

docker run -d --name web -p 8080:80 nginx:alpine
python3 -m http.server 8081

From the other machine:

curl http://server:8080/   ->  HTTP 200 (Docker's port answers)
curl http://server:8081/   ->  no answer (ufw blocks the host's port)

Why Docker bypasses ufw

Docker added a rule to the nat table that rewrites the destination of anything arriving on port 8080:

$ sudo iptables -t nat -S DOCKER
-N DOCKER
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80

That rewrite happens in PREROUTING, before the kernel decides where the packet goes. Once its destination is the container's address, the packet is no longer for the host: it is forwarded, and forwarded packets pass through the FORWARD chain, never through INPUT. ufw's rules for incoming traffic are in INPUT. In FORWARD, Docker's chains come first:

$ sudo iptables -S FORWARD
-P FORWARD DROP
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-FORWARD
-A FORWARD -j ufw-before-logging-forward
...

Docker's chains accept the traffic for published ports before ufw's forward rules are reached. Docker's documentation describes the same path: packets are diverted in the nat table "before it reaches the INPUT and OUTPUT chains that ufw uses".

Check your own server

List what each container publishes:

sudo docker ps --format 'table {{.Names}}\t{{.Ports}}'

A port shown as 0.0.0.0:5432->5432/tcp or [::]:6379->6379/tcp is published on every address the server has, the public one included. A port shown as 127.0.0.1:3000->3000/tcp is published on the server only. On a typical web server, only the reverse proxy should show 0.0.0.0, on 80 and 443.

Then test from another machine, not from the server itself (on the server everything answers):

nc -zv -w 3 your-server 5432

A database port that answers here is a database open to the internet, protected only by its password.

Fix 1: publish only on 127.0.0.1, or not at all

Most services behind a reverse proxy don't need a published port. In Compose, services on the same project network reach each other by service name, so Caddy (opens in a new tab) or nginx can send traffic to app:3000 with no ports: entry on app at all. When something on the host itself needs the port (a backup script, a tunnel, a debugging session), publish it on the loopback address only:

services:
  app:
    image: ghcr.io/you/app:latest
    ports:
      - "127.0.0.1:3000:3000"

On the command line it is -p 127.0.0.1:3000:3000. In our test, a service published this way answered on the server (curl http://127.0.0.1:8080/ gave 200) and not from the other machine, while a second service in the same Compose file, published as "8090:80", answered from everywhere.

Warning

Docker's documentation warns that in releases older than 28.0.0, hosts on the same layer-2 network (for example, other machines on the same switch) could reach ports published to localhost. Check docker version and upgrade if your Engine is older.

Make 127.0.0.1 the default

To stop relying on every Compose file being written carefully, change the default address in /etc/docker/daemon.json. Two settings are needed, because the first applies only to Docker's default bridge and the second to the networks Compose creates:

{
  "ip": "127.0.0.1",
  "default-network-opts": {
    "bridge": {
      "com.docker.network.bridge.host_binding_ipv4": "127.0.0.1"
    }
  }
}

Restart Docker (sudo systemctl restart docker) and recreate the containers (docker compose down then docker compose up -d): networks that already exist keep their old default. In our test, after the change "8090:80" in Compose and -p 8070:80 on the command line were both published on 127.0.0.1 only.

Your reverse proxy must then name the public address explicitly, or it will be unreachable too:

services:
  caddy:
    image: caddy:2
    ports:
      - "0.0.0.0:80:80"
      - "0.0.0.0:443:443"

In our test, a port written with 0.0.0.0 answered from outside. It is published on IPv4 only, so if your domain has an AAAA record, add "[::]:80:80" and "[::]:443:443" as well.

Fix 2: the provider's firewall in front

A firewall in the provider's network sits outside your server, so nothing Docker writes on the server affects it. Hetzner Cloud Firewalls and DigitalOcean Cloud Firewalls cost nothing, and both block inbound traffic that no rule allows. For a web server, allow:

  • TCP 22 for SSH (from your own addresses only, if you can);
  • TCP 80 and 443 for the web;
  • UDP 443 if your proxy serves HTTP/3.

Then even a mistaken ports: - "5432:5432" stays unreachable from the internet. We describe setting one up step by step in deploying a Docker Compose app to Hetzner and deploying to a DigitalOcean Droplet. We didn't test these firewalls; they need a real account.

Keep ufw on the server as well: it still protects everything that listens on the host itself, and it is the only firewall when the server is somewhere without one.

Fix 3: rules in the DOCKER-USER chain

For a rule that has to live on the server, such as "port 8090 only from our office", use DOCKER-USER, an iptables chain that Docker creates empty and jumps to before its own rules, for every forwarded packet. Docker doesn't remove what you put there when it restarts; in our test, a rule survived systemctl restart docker.

One detail matters: by the time a packet reaches DOCKER-USER, its destination has already been rewritten to the container's address and port. To match the port the visitor connected to, Docker's documentation uses the conntrack match (--ctorigdstport). We add --ctdir ORIGINAL, explained below:

sudo iptables -I DOCKER-USER -i eth0 -p tcp \
  -m conntrack --ctorigdstport 8090 --ctdir ORIGINAL \
  ! -s 203.0.113.10 -j DROP

This drops connections to published port 8090 that arrive on eth0, the public interface, from anyone except 203.0.113.10. --ctdir ORIGINAL limits the match to packets in the direction of the new connection, so replies to connections your containers make themselves are never caught. Find your public interface with ip route show default. In our test, the other machine got no answer on 8090, an allowed address got 200, and the container could still reach the internet.

Docker's documentation also shows a broader rule, iptables -I DOCKER-USER -i ext_if ! -s 192.0.2.2 -j DROP, which lets only one source address through that interface. As written, it also drops the replies to connections your containers open themselves: in our test, a container could no longer resolve a host name or reach a website. If you want that rule, let established connections through first. Run the commands in this order, because -I puts each rule at the top:

sudo iptables -I DOCKER-USER -i eth0 ! -s 192.0.2.2 -j DROP
sudo iptables -I DOCKER-USER -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN

With both rules, the container reached the internet again and a stranger still got no answer.

These rules cover IPv4. Docker creates a DOCKER-USER chain for IPv6 too; use ip6tables with the same rules if your containers are reachable over IPv6.

Keep the rules after a reboot

iptables rules live in memory, so they are gone after a reboot. Load them from a small script that runs before Docker starts. The script, /usr/local/sbin/docker-user-filter:

#!/bin/sh
# Rules for published Docker ports, loaded before Docker starts.
set -e
iptables -N DOCKER-USER 2>/dev/null || true
iptables -F DOCKER-USER
# Port 8090 only from 203.0.113.10; everyone else is dropped.
iptables -A DOCKER-USER -i eth0 -p tcp -m conntrack --ctorigdstport 8090 --ctdir ORIGINAL ! -s 203.0.113.10 -j DROP

And its unit, /etc/systemd/system/docker-user-filter.service:

[Unit]
Description=Firewall rules for published Docker ports (DOCKER-USER)
Before=docker.service
After=ufw.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/docker-user-filter

[Install]
RequiredBy=docker.service

Turn it on:

sudo chmod 755 /usr/local/sbin/docker-user-filter
sudo systemctl daemon-reload
sudo systemctl enable docker-user-filter.service

RequiredBy=docker.service makes the filter a requirement of Docker. We tested both sides: after restarting the test machine (a fresh systemd boot with empty firewall tables), the rule was back before Docker started and the port stayed closed to strangers; and with the script made to fail, systemctl start docker refused with "A dependency job for docker.service failed". The site goes down rather than coming up without its filter. If you prefer the opposite, use WantedBy= instead.

What not to do

  • Don't set "iptables": false. Docker's documentation says it "is likely to break container networking": containers lose outbound internet access, and, with no replacement rules, their ports are reachable from the local network. It also says that writing those rules yourself is "extremely involved".
  • Don't edit Docker's own chains or tables. Docker owns them and rewrites them; Docker's documentation asks you not to modify them.
  • Don't trust a scan from the server itself. Everything answers on the server. Only a connection from outside shows what is exposed.

Docker 29 and nftables

Docker Engine 29.0.0 added a second firewall backend, nftables, chosen with "firewall-backend": "nftables" in daemon.json. Its documentation calls it experimental, and iptables stays the default: docker info on our test server showed Firewall Backend: iptables. With nftables there is no DOCKER-USER chain; your rules go in a table of your own, with base chains on the same hooks as Docker's and a priority that orders them. Docker also stops enabling IP forwarding by itself under nftables. The ufw problem changes rather than goes away: ufw's default forward policy is DROP (DEFAULT_FORWARD_POLICY in /etc/default/ufw), and Docker's documentation warns that an iptables FORWARD chain with policy DROP drops packets Docker's nftables rules accepted, so port publishing doesn't work until that policy is removed. We didn't test the nftables backend. Until it is stable, the iptables backend with DOCKER-USER is the documented path.

Doing this with OpsCrew

OpsCrew, an open-source tool that deploys apps to servers you own, keeps every container port on the server except the proxy's 80 and 443, and sets up a firewall that lets in only SSH and web traffic (what OpsCrew sets up). On a server you already have, it installs Docker Engine 28 or newer, which its guide notes "keeps ports that are published only on the server itself really local" (your own server).

When you choose to serve directly behind Cloudflare (opens in a new tab)'s proxy, OpsCrew puts its Cloudflare-only filter in the DOCKER-USER chain, "because ports that Docker publishes bypass ufw", and it fails closed: if the filter can't be installed when the server starts, Docker doesn't start either. Origin protection adds a client certificate so only Cloudflare acting for your zone gets through. npx opscrew secure checks the ports that answer from outside.

Next on the checklist

The next step in the Ubuntu server hardening checklist is keeping the system patched with automatic security updates; if you haven't locked down logins yet, start with securing SSH.

Key facts

FactValueSource
Docker's documentation on ufw"Docker and ufw use firewall rules in ways that make them incompatible with each other."Docker documentation, Packet filtering and firewalls (opens in a new tab)Verified on
Default address for a published portAll host addresses (0.0.0.0 and [::]) unless you name oneDocker's documentation: "Publishing container ports is insecure by default."Docker documentation, Port publishing and mapping (opens in a new tab)Verified on
Ports published to 127.0.0.1 before Docker 28.0.0Reachable from hosts on the same layer-2 networkDocker documentation, Port publishing and mapping (opens in a new tab)Verified on
Docker's nftables backendIntroduced in Docker 29.0.0, experimental; iptables remains the defaultWith nftables there is no DOCKER-USER chain; rules go in a table of your own.Docker documentation, Docker with nftables (opens in a new tab)Verified on
Versions in this article's testsUbuntu 24.04.5 LTS, Docker Engine 29.9.3 (iptables backend), ufw 0.36.2Tested on 11 November 2026 in containers running systemd, with Docker installed from Docker's apt repository.Install Docker Engine on Ubuntu (opens in a new tab)Verified on

Frequently asked questions

How do I block a Docker container port with ufw?

You can't do it reliably with ufw's normal rules. Bind the port to 127.0.0.1 instead, block it in the provider's firewall, or add a rule to Docker's DOCKER-USER chain, which Docker evaluates before its own rules.

Does this also happen with firewalld?

Yes. Docker's installation guide warns that with ufw or firewalld, ports you expose with Docker bypass your firewall rules. With firewalld, Docker puts its bridges in a zone called docker with target ACCEPT.

Sources

  1. Packet filtering and firewalls (opens in a new tab), Docker, accessed on
  2. Docker with iptables (opens in a new tab), Docker, accessed on
  3. Docker with nftables (opens in a new tab), Docker, accessed on
  4. Port publishing and mapping (opens in a new tab), Docker, accessed on
  5. iptables-extensions(8), the conntrack match (opens in a new tab), netfilter project, accessed on
  6. Install Docker Engine on Ubuntu (opens in a new tab), Docker, accessed on
  7. Hetzner Cloud Firewalls overview (opens in a new tab), Hetzner, accessed on
  8. DigitalOcean Cloud Firewalls (opens in a new tab), DigitalOcean, accessed on
Edit this article
  • Deploying

    Deploy a Docker app to a DigitalOcean Droplet

    Create a Droplet, lock it down with a Cloud Firewall, install Docker from Docker's own repository, and run your app with Compose and automatic HTTPS. Every command tested; prices checked on 11 November 2026.

    8 min read

  • Deploying

    Cloudflare Tunnel for a self-hosted app: setup, Docker and SSH

    What a Cloudflare Tunnel is, quick tunnels and named tunnels, a tested Docker Compose setup with a tunnel token, SSH through Cloudflare Access, and the limits that come with sending every request through Cloudflare.

    11 min read

  • Deploying

    Migrate a Heroku app and its Postgres database to a VPS

    A tested migration from Heroku to your own server: the Procfile as Docker Compose services, config vars to a file, Scheduler to supercronic, Heroku Postgres restored with pg_restore, a DNS cutover and a way back.

    13 min read

Put OpsCrew to work on your app.

Run npx opscrew init in your app's repository. It checks your tools and tokens first, for free.