简体   繁体   中英

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM