You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Docker Python API在指定IP上运行iperf容器?

Replicating docker run for iperf3 with fixed IP via Docker Python API

Hey there! Let's break down how to translate your docker run command into working Python code using the Docker API. Your original command does a few key things: runs the iperf3 server in detached mode, names the container iperf_srv, attaches it to the mynet network, assigns a fixed IP of 10.195.10.10, and starts the server with the -s flag.

The Issue with Your Existing Code

Your current snippet is setting up an IPAM pool, but that's for creating a new network with a custom IP range. Since you're already using an existing network (mynet), you don't need to define an IPAM pool here—you just need to specify the fixed IP when launching the container.

Working Code Example

Here's the complete code that matches your docker run command exactly:

import docker

# Initialize the Docker client
client = docker.from_env()

# Run the iperf3 container with all the required parameters
iperf_container = client.containers.run(
    image='astotal/iperf3',
    command=['-s'],  # The server flag for iperf3
    detach=True,     # Equivalent to `-d` in docker run
    name='iperf_srv',# Equivalent to `--name iperf_srv`
    network='mynet', # Equivalent to `--network mynet`
    ipv4_address='10.195.10.10'  # Equivalent to `--ip 10.195.10.10`
)

# Optional: Print the container ID to confirm it's running
print(f"iperf3 server container started with ID: {iperf_container.id}")

Key Parameter Breakdown

Let's map each Python parameter to your original docker run flags:

  • detach=True: Matches -d (runs container in background)
  • name='iperf_srv': Matches --name iperf_srv
  • network='mynet': Matches --network mynet
  • ipv4_address='10.195.10.10': Matches --ip 10.195.10.10
  • command=['-s']: Matches the final -s argument to start iperf3 as a server

What If mynet Doesn't Exist?

If you need to create the mynet network first (with the correct subnet for your fixed IP), you can add this code before running the container:

# Check if the network exists; create it if not
try:
    mynet = client.networks.get('mynet')
except docker.errors.NotFound:
    mynet = client.networks.create(
        name='mynet',
        driver='bridge',
        ipam=docker.types.IPAMConfig(
            pool_configs=[
                docker.types.IPAMPool(
                    subnet='10.195.10.0/24',
                    iprange='10.195.10.0/24'
                )
            ]
        )
    )

This creates the network with the subnet you defined in your original snippet, ensuring the fixed IP you want is valid for the network.

内容的提问来源于stack exchange,提问作者Anton Kharchenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:28:46