Iptables – Forward one IP to a docker container

dockeriptablesnetworking

As far as I understood, docker run containers with their own IPs, and fully open ports, on the bridge interface docker0.

Let's say I launch a container, and it has its own IP: 172.17.0.11, and I have a virtual ethernet interface, eth0.1, with public IP 93.x.x.x

How do I forward eth0.1 to the docker container, so that I can reach the container via eth0.1 IP?

Can I forward all ports at once? (maybe with a script)

How do I disable docker default behavior, so that each container only gets an IP on docker0 interface, and I manually setup forwarding?

@Xavierlucas

I linked it because I thought it was explained better over there. If you check the debian config, I add to the /etc/net/interfaces file this:

post-up /sbin/ifconfig eth0:X IP.OF.FAIL.OVER netmask 255.255.255.255 broadcast IP.OF.FAIL.OVER
post-down /sbin/ifconfig eth0:X down

this way I have a virtual interface (eth0:0), which has a public IP forwarded by my provider. I think the routing is done by the provider,as there are no additional routes or configs on my server

Note:

There is a followup question

why port forwarding is not working in this setup?

Best Answer

Firstly you wouldn't want to forward all ports at once, as then you wouldn't necessarily still have access to the host. This should definitely be a manual process.

I expect that you have a web service running in your Docker container, so if you wish to forward, for example port 80 from your eth0.1 IP address to the Docker container's IP address you could use the following iptables rule;

iptables -A PREROUTING -t nat -i eth0.1 -p tcp --dport 80 -j DNAT --to 172.17.0.11:80
iptables -A FORWARD -p tcp -d 172.17.0.11 --dport 80 -j ACCEPT

These rules can then be modified for any other ports/docker containers as required.

Related Topic