How to use UFW with Docker // ufw-docker
Why you need it
Docker publishes ports by inserting its own iptables rules before UFW can see them.
A normal ufw deny 8080 does nothing.
ufw-docker fixes this by making Docker traffic go through UFW’s rules.
PrerequisitesUbuntu / Debian (or any distro with UFW)
Docker already installed and working UFW preferably already enabled
Make sure Docker’s iptables management is enabled (default):
# Check (should NOT have "iptables": false)
cat /etc/docker/daemon.json
##. Install ufw-docker
# Download the script
sudo wget -O /usr/local/bin/ufw-docker \
https://github.com/chaifeng/ufw-docker/raw/master/ufw-docker
# Make it executable
sudo chmod +x /usr/local/bin/ufw-docker
Install the necessary UFW rules:
sudo ufw-docker install
This backs up /etc/ufw/after.rules and adds the required Docker-aware rules.
Reload UFW:
sudo ufw reload
# or
sudo systemctl restart ufw
(Optional but recommended) Install the systemd service so rules stay updated:
sudo ufw-docker install-service
Basic UFW setup
# Set defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Always allow SSH (change port if needed)
sudo ufw allow 22/tcp
# or: sudo ufw allow 2222/tcp
# Enable UFW
sudo ufw enable
How to allow / deny Docker containers
Important concept:
You allow the container port, not the host port.
Example:
docker run -d --name web -p 8080:80 nginx
→ You allow port 80 (the container’s port).
Allow a container
# Allow all published ports of the container
sudo ufw-docker allow web
# Allow only a specific port
sudo ufw-docker allow web 80
sudo ufw-docker allow web 80/tcp
sudo ufw-docker allow web 53/udp
Allow only from a specific IP / network
sudo ufw-docker allow web 80 from 203.0.113.50
sudo ufw-docker allow web 80 from 192.168.1.0/24
Delete rules
# Remove all rules for the container
sudo ufw-docker delete allow web
# Remove a specific port
sudo ufw-docker delete allow web 80
Useful commands
ufw-docker status # Show current Docker-related rules
ufw-docker list web # Show rules for a specific container
ufw-docker check # Verify installation
ufw-docker help # Full help
No comments to display
No comments to display