Block port on Docker containers using iptables

I have a service running on port 3007 in Docker, it's set up like this:

services:
    api:
        ports:
        - 3007:80

I tried adding a rule to the DOCKER-USER chain to block nonlocal traffic on that port:

iptables -I DOCKER-USER -p tcp --dport 3007 ! -s 127.0.0.1 -j DROP

However, this didn't work. Looking at the rules on the DOCKER chain it seems like the forwarded ports are the the ones on the inside of the container (80 and not 3007), so I'm not sure how to go about managing access to them.


Solution 1:

Bind the exposed port to the loopback interface.

services:
    api:
        ports:
        - "127.0.0.1:3007:80"