Advanced Docker networking // Custom outgoing IP

Copyright © 2017 Docker Inc., Source https://github.com/docker/machine

Docker Networking

I didn’t have in depth knowledge about how Docker manages its containers networking. So I went ahead and started reading https://docs.docker.com/engine/userguide/networking/

Masquerade

Let’s break down the magic instruction -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE

  • belongs to the chain -A POSTROUTING which allows modifying routed packets.
  • applies to packets coming from the subnet -s 172.17.0.0/16 that are not going to be sent via the interface ! -o docker0 where the latter is Dockers default bridge interface and the former is its IPv4 subnet.
  • instructs to jump to -j MASQUERADE which assigns the corresponding IP of the outgoing interface to matching packets.

Let’s do it

To verify that everything is working out I’m using a docker container to query my current IP via http://www.myip.ch .

  • belongs to the POSTROUTING chain of the nat table, so nothing changed.
  • applies to packets coming from the subnet-s 172.18.0.0/16 that are not going to be sent via the interface ! -o bridge-coi where the latter is our new bridge interface and the former is its IPv4 subnet, which you can either specify yourself or check with command docker network inspect bridge-coi .
  • instructs to jump to -j SNAT while giving the instruction to assign the source IP 5.104.xxx.xxx to all matching packets.

Final words

Despite being an advanced topic we saw that it’s achievable with a little bit of effort. I quite enjoyed working on this and I hope you had fun reading my story.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store