Search code examples
dockernetwork-programmingfirewalliptables

Docker: limit outgoing connections to the localhost only, while allowing all incoming connections


Some programs in my docker container are making unwanted requests to e.g. Google Analytics and other tracking software, sharing my information. I want to block all this traffic, while still being able to access the docker from outside.

I tried adding the --network=host, this worked correctly, only allowing localhost access from inside the container, but also blocked all external incoming connections.

Is there a way to limit the outgoing connections to the localhost only, while still allowing incoming external connections? I only want to enforce this on a specific docker container, not for my entire system.

Any feedback is appreciated.


Solution

  • I found a working solution for my problem in another thread:

    docker network create --subnet 172.19.0.0/16 no-internet
    sudo iptables --insert DOCKER-USER -s 172.19.0.0/16 -j REJECT --reject-with icmp-port-unreachable
    sudo iptables --insert DOCKER-USER -s 172.19.0.0/16 -m state --state RELATED,ESTABLISHED -j RETURN
    

    When starting a docker container add:

    --network no-internet
    

    After this, I cannot connect to the internet from inside the container. However, I can still access the container ports from the outside.