© 2021 www.richardwalz.com
Richard Walz
All rights reserved.

IP Whitelist Docker Containers with UFW (the better way).

The Problem:

We need to block access to the docker containers, but only allow specific IP addresses to connect. We only want the following IP addresses to be allowed to connect to the docker containers

  • 192.168.86.10
  • 192.168.86.11

The solution:

  1. Install UFW. If you need to reset UFW rules check out this post
apt-get install ufw
  1. use your favorite editor (I prefer nano) and edit the “after.rules” files
nano /etc/ufw/after.rules

3. Modify the file with the below (for most users this means replace the existing with the below)

#BEGIN UFW AND DOCKER
*filter
:ufw-user-forward - [0:0]
:ufw-docker-logging-deny - [0:0]
:DOCKER-USER - [0:0]
-A DOCKER-USER -j ufw-user-forward

#IPs allowed to connect to Docker/Containers
-A DOCKER-USER -j RETURN -s 192.168.86.11/32
-A DOCKER-USER -j RETURN -s 192.168.86.10/32

#Allow DNS
-A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN

#State from where you want logging enabled. This will log all internal IPs
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12

-A DOCKER-USER -j RETURN

-A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] "
-A ufw-docker-logging-deny -j DROP

# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT
  1. Enable and reload the firewall so access is updated
sudo ufw enable
sudo ufw reload
  1. In very rare cases you may need to restart the docker server for the rules to take affect.

Still not working?

Ensure the following files are blank or do not have the following value in them: DOCKER_OPTS=”–iptables=true”

nano /etc/docker/daemon.json
nano /etc/default/docker

Source: https://github.com/chaifeng/ufw-docker