Home > other >  How to run a docker container with a previously determined ip address with the python docker sdk?
How to run a docker container with a previously determined ip address with the python docker sdk?

Time:01-20

On console this does the trick:

docker run --net mynet --ip 172.18.0.22 --dns="8.8.8.8" -d testimage

is there an easy equivalent with the python docker sdk like this?

container = client.containers.run("alpine", "ls /", detach=True, ipv4_address=ip_address)

but there is no ipv4_address param in the run function...

CodePudding user response:

The IP address of a container only exists in reference to whichever network the container is being connected to at that IP, so you need to specify it on the network connection, not container creation.

This becomes a two-step process in the Python SDK. Assuming the network mynet already exists, you can connect your container to it after creation using Network.connect. The equivalent of your console command would be something like:

container = client.containers.run("testimage", detach=True, dns=["8.8.8.8"])
mynet = client.networks.list(names=["mynet"])[0]
mynet.connect(container, ipv4_address="172.18.0.22")
  • Related