Assign LAN IP address to Docker container different from host's IP address

前端 未结 2 1181
梦毁少年i
梦毁少年i 2020-12-09 12:54

Am not well versed with Unix networking, adding virtual interfaces etc, trying to learn it now. We are trying to dockerize our application.
My requirement is : To assign

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 13:34

    My current preferred approach with this is to use either the macvlan or ipvlan Docker network driver. I prefer macvlan as each container can have its own MAC address but some things like VMware don’t like having multiple Mac addresses for a single virtualized nic and won’t route traffic properly.

    Setup is pretty straight forward. First you need to determine a few things.

    • Subnet of your main network. Using 10.0.0.0/24 for this example
    • Gateway of your network. Using 10.0.0.1 for the example
    • IP range to use for allocating the ips from (you can statically assign ips outside this range when doing a Docker run if need be). For this example I will use 10.0.0.128/25. You will need a chunk of ips to let Docker manage so you will need to ensure these ips are not in use on your network.
    • The name of the device you want to use for the traffic. For the example I will use eth0
    • The name of the new Docker network you are going to create. Using “my net” for the example.

    Next you create a new Docker network like so:

    docker network create -d macvlan —-subnet 10.0.0.0/24 --ip-range 10.0.0.128/25 —-gateway 10.0.0.1 -o parent=eth0 mynet
    

    Now when you start containers use

    docker run —-network mynet .....
    

    For more information see the docker docs: https://docs.docker.com/engine/userguide/networking/get-started-macvlan

    One caveat to this approach is that macvlan/ipvlan dont seem to work very well with Docker for Mac. The HyperKit vm it creates is a bit of a black box. The macvlan/ipvlan approach requires a more controlled network that Docker for Mac doesn't give you. If you are trying to do this with Docker for Mac then I would suggest setting up a Docker Machine. The docs for how to do that are here: https://docs.docker.com/machine/get-started/.

    In this scenario, unless you like setting up routing rules on your Mac, you should have the docker machine use a bridged interface that the macvlan/ipvlan network can then be attached to. In my experience the need for a second NIC that is NAT'ed through the MacOS host is unnecessary but you may find something otherwise.

提交回复
热议问题