Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker-py: How to bind an IP address to a container

Say I have a network called "mynet" and I want to start a container with an IP address bound to 192.168.23.2.

The code I'm starting with is:

import docker
c = docker.from_env()
c.containers.run('containername', 'sh some_script.sh', network='mynet')

What do I do from here? I'm effectively looking for the equivalent to the --ip option from docker run.

like image 421
markzz Avatar asked Oct 04 '17 01:10

markzz


People also ask

Can you assign an IP to a Docker container?

When you connect an existing container to a different network using docker network connect , you can use the --ip or --ip6 flags on that command to specify the container's IP address on the additional network. In the same way, a container's hostname defaults to be the container's ID in Docker.


1 Answers

You need to create a network and connect the container to it:

container = c.containers.run('containername', 'sh some_script.sh')

ipam_pool = docker.types.IPAMPool(
    subnet='192.168.23.0/24',
    gateway='192.168.23.1'
)
ipam_config = docker.types.IPAMConfig(
    pool_configs=[ipam_pool]
)
mynet= c.network.create(
    "network1",
    driver="bridge",
    ipam=ipam_config
)

ip = {"ipv4_address": "192.168.23.2"}
mynet.connect(container,ip)
like image 90
anhlc Avatar answered Oct 19 '22 15:10

anhlc