Docker Community Forums

Share and learn in the Docker community.

Assign Container IP adress from same network as host


(Grexaut) #1

Hello,

I know there are some questions like this Docker. Assign IP from the same range as Host - but there are all 2-3 years old that I found. I would like know, what is the best practice solution for the followng task:
I have my docker host with the following Network settings:

IP: 192.168.0.2
Subnet: 255.255.255.0
GW: 192.168.0.1

The host has an additonal IP: 192.168.0.3

And I have an docker container with icinga2 image, with following addional options:
-p 192.168.0.3:80:80 \
-p 192.168.0.3:443:443 \
-p 192.168.0.3:5665:5665 \

So I’m able to connect from my client (192.168.0.4) to Webserver and API from 192.168.0.4 to 192.168.0.3

All traffic from the container (e.g. ping 192.168.0.1 from bash inside the container) have as source: 192.168.0.2, but I want 192.168.0.3 as souce IP.

I tried with bridged Network, but then the host container is not reachable anymore.

I read something about macvlan, as documented it is for legacy application, but is this the only solution?

Maybe someone could help me.


(Sam) #2

good luck… i have been trying to do this reliably for a few years without success.

you need to assign the ip address to the container when it starts (docker run --ip xxx.yyy.zzz.qqq and probably a mac address too --mac …etc…

i wrote some scripts which do all the work, and they work great on my physical hardware linux machine, and do not work in any Virtual machine.

see the script parts here
https://forums.docker.com/t/new-to-docker-need-assistance/47302


(Grexaut) #3

Hi,

I’m afraid that this is not so easy what I want… But I found an other acceptable solution.

First I added a own network,
docker network create --subnet=172.18.0.0/16 mynetwork

Starting the container with option --net mynetwork --ip 172.18.0.3

Then I create an iptables rule:
iptables -t nat -R POSTROUTING 1 -s 172.18.0.3 -j SNAT --to 192.168.0.3

If I request any traffic from container with IP 172.18.0.3 it will be natted with 192.168.0.3, the source traffic is now 192.168.0.3 and not the container main host IP 192.168.0.2


(Sam) #4

Cool. Nice work.

Sadly the application I am fighting takes the IP address inside the container, and puts that inside a data packet to another component which uses that address to open a return connection. But the container address cannot be reached from a machine on the other side of the network