Docker Community Forums

Share and learn in the Docker community.

Restricting exposed Docker ports with iptables

Dear Community!

I want to restrict general Docker exposed ports access.
Most of my exposed ports are using reverse-proxy so it will be enough if these exposed ports will be only accessible through localhost.

I know that I could do 127.0.0.1:8080:80 port mapping in Docker, but it will be better for me if simply doing a -p 8080:80 would only allow access from localhost.

Right now for testing, I have a port mapped like this in a docker-compose.yml file:

ports:
     - 222:22

I have added a rule like this to the DOCKER-USER chain, but I can still access this 222 port from outside:

-A DOCKER-USER -i eth0 -p tcp -m tcp --dport 222 -j DROP
-A DOCKER-USER -j RETURN

Why this rule is not working?

Also there are a few ports which should be accessible from our VPN network.
So I would think that a DROP policy on the DOCKER-USER chain would be great for me and then I would allow these specific ports.

Can someone help me debug this and get it working?

Thanks!

I have also found Steps for limiting outside connections to docker container with iptables? - Server Fault

For example:

iptables -A DOCKER-USER -i eth0 -s 8.8.8.8 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j ACCEPT
iptables -A DOCKER-USER -i eth0 -s 4.4.4.4 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j ACCEPT
iptables -A DOCKER-USER -i eth0 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j DROP

I’m using the DOCKER-USER chain only for Docker related iptables rules.
The rules seems really great, but I don’t know how I can apply this generally for all ports.
So I don’t want to create a new rule for every newly opened port like this one:

iptables -A DOCKER-USER -i eth0 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j DROP

and then define specific rules for each port. I want something general which defaults to drop for all ports.

That would be really great, because multiple users are creating Docker containers on this server and I don’t want new ports to get exposed automatically, just by adding a manual ACCEPT rule for each port.