Docker – How to utilize UFW blocking published ports from docker

dockerufw

Might seem a silly question but i'm trying to get the following to work:

  • I have a correctly configured UFW for only allowing certain source IPs access to my local service
  • after migrating this service into a docker container with a published port the port is publicly published

Thus every host can now access the published port from anywhere.

How can I restrict access via UFW to this published docker port?

The specific port this service is using is 3333.

I've tried to get it to work using -p 127.0.0.1:3333:3333 in order to bind the port to localhost. But then I'd need a proxy to go from the UFW-restricted public port to localhost:3333. I also tried to use iptables -j REDIRECT, but I couldn't get it to work.

So it's not a problem of the container restricting access to outside, it outside getting to the container.

I'd like to keep my current UFW setup with explicit whitelisting for Dockerized serviced.

Best Answer

I've found out a better more consistent solution in advance of the new docker iptables solution coming in 1.5+.

By not using the FORWARD chain but another the rules are handled before docker alters the iptable chains and thus will survive docker container restarts. If anyone ever needs it: this solved my issue of having custom iptable rules and docker on a host:

iptables -I PREROUTING 1 -t mangle ! -s [SOURCEIP_TO_ALLOW] -p tcp --dport [PORT] -j ACCEPT
iptables -I PREROUTING 2 -t mangle -p tcp --dport [PORT] -j DROP

The trick is the PREROUTING and mangle step. This way i can allow from SOURCEIP_TO_ALLOW on PORT on the host and disallow others coming in...!