user1200794
user1200794

Reputation: 177

Limit Network access but allow a specific IP for a Running Docker Container

I try to use a docker container where only a specific IP address should be accessible out of the running container. iptables are only working in priviliged docker container. But than the user can change the iptables themselves. A nice idea would be to create a docker image with a dockerfile and with iptables. But there is no option for privileged right while creating an image. Anyone have an idea how to solve this issue?

Best

Upvotes: 3

Views: 3264

Answers (1)

larsks
larsks

Reputation: 312790

Each docker container has a unique IP address, so if you want to permit a container with address 172.17.0.21 and you want it to be able to only access address 8.8.8.8, you could do something like:

iptables -A FORWARD -s 172.17.0.21 -d 8.8.8.8 -j ACCEPT
iptables -A FORWARD -s 172.17.0.21 -j REJECT --reject-with icmp-host-prohibited

It is also possible to modify the iptables rules inside an unprivileged container using the nsenter command. For example, if you start a Docker container:

docker run --name example -d myimage

You can get the PID of that container like this:

pid=$(docker inspect -f '{{.State.Pid}}' example)

And then use nsenter to run commands inside that container's network namespace:

nsenter -t $pid -n iptables ...

These commands will run without the capabilities restrictions of commands run inside the container.

Upvotes: 3

Related Questions