Skip to content

Instantly share code, notes, and snippets.

@josectheone
Created October 14, 2019 11:35
Show Gist options
  • Save josectheone/ac74c1780f5f10567c73a826f359e64d to your computer and use it in GitHub Desktop.
Save josectheone/ac74c1780f5f10567c73a826f359e64d to your computer and use it in GitHub Desktop.
Docker and UFW solution
1 - Add this lines to the end of /etc/ufw/after.rules
# BEGIN UFW AND DOCKER
*filter
:ufw-user-forward - [0:0]
:DOCKER-USER - [0:0]
-A DOCKER-USER -j RETURN -s 10.0.0.0/8
-A DOCKER-USER -j RETURN -s 172.16.0.0/12
-A DOCKER-USER -j RETURN -s 192.168.0.0/16
-A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN
-A DOCKER-USER -j ufw-user-forward
-A DOCKER-USER -j DROP -d 192.168.0.0/16 -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN
-A DOCKER-USER -j DROP -d 10.0.0.0/8 -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN
-A DOCKER-USER -j DROP -d 172.16.0.0/12 -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN
-A DOCKER-USER -j DROP -d 192.168.0.0/16 -p udp -m udp --dport 0:32767
-A DOCKER-USER -j DROP -d 10.0.0.0/8 -p udp -m udp --dport 0:32767
-A DOCKER-USER -j DROP -d 172.16.0.0/12 -p udp -m udp --dport 0:32767
-A DOCKER-USER -j RETURN
COMMIT
# END UFW AND DOCKER
2 - Using command sudo systemctl restart ufw or sudo ufw reload to restart UFW after changing the file. Now the public network can't access any published docker ports, the container and the private network can visit each other normally, and the containers can also access the external network from inside. There may be some unknown reasons cause the UFW rules will not take effect after restart UFW, please reboot servers.
If you want to allow public networks to access the services provided by the Docker container, for example, the service port of a container is 80. Run the following command to allow the public networks to access this service:
ufw route allow proto tcp from any to any port 80
This allows the public network to access all published ports whose container port is 80.
Note: If we publish a port by using option -p 8080:80, we should use the container port 80, not the host port 8080.
If there are multiple containers with a service port of 80, but we only want the external network to access a certain container. For example, if the private address of the container is 172.17.0.2, use the following command:
ufw route allow proto tcp from any to 172.17.0.2 port 80
If the network protocol of a service is UDP, for example a DNS service, you can use the following command to allow the external network to access all published DNS services:
ufw route allow proto udp from any to any port 53
Similarly, if only for a specific container, such as IP address 172.17.0.2:
ufw route allow proto udp from any to 172.17.0.2 port 53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment