robertselkirkknox
robertselkirkknox

Reputation: 21

how to assign-static-ip-to-docker-container in docker-py

I think I know how to assign a static ip in docker. Something like this seems to work:

docker run -it --rm --net=br0 --cap-add=NET_ADMIN --ip=172.27.153.11 mbussim

The problem is doing this in docker-py, which I think is just a python docker interface to docker.

In principle, docker-py tries to follow the docker lead:

You would think something like this would work:

options = { "detach": True, "ip": "172.27.153.11", #"remove": True, "name": "mbussim_" + str(count), "cap_add": "NET_ADMIN" } }

       self.dockcon = self.dockerclient.containers.run(self.dimg, **options)

However, this does not work. Perhaps, this is not possible it docker-py?

Upvotes: 2

Views: 1134

Answers (1)

Zee
Zee

Reputation: 11

Following this seems to work. First create an ip subnet:

ipam_pool = docker.types.IPAMPool(
    subnet='192.168.0.0/16',
    gateway='192.168.0.254'
)
ipam_config = docker.types.IPAMConfig(
    pool_configs=[ipam_pool]
)
client.networks.create(
    "mynet",
    driver="bridge",
    ipam=ipam_config
)

Now create the container the usual way:

container = client.containers.run("ubuntu", ["sh", "-c", command()], detach=True)

This by default attaches the container to a bridge network. Now attach your container to your network and assign the static ip you want from the subnet.

client.networks.get("mynet").connect(container, ipv4_address="192.168.10.5")

Your container will now have 2 interfaces eth0 for the default network and eth1 having the mynet interface. I am sure there must be an easier way to achieve this.

Upvotes: 1

Related Questions