我尝试使用 docker-py(版本 1.3.1)启动一个 docker 容器。我想将容器内部端口映射到不同的端口,但无法正确公开它们。
我这样做是这样的:
def start_container(client, host_config, image_tagged_name, command):
print ("create_host_config", host_config.binds, host_config.port_bindings)
the_host_config = create_host_config(binds = host_config.binds,
port_bindings = host_config.port_bindings);
the_ports = host_config.port_bindings.values();
print ("create_container", image_tagged_name, command, the_ports, the_host_config)
cont_id = client.create_container(image=image_tagged_name, command=command, ports=the_ports, host_config=the_host_config)["Id"]
在手头的情况下,输出如下:
create_host_config ['/dbfiles/test:/opt/db'] {3001: 3000, 2425: 2424, 2481: 2480}
create_container test:test ./initdb.sh [3000, 2424, 2480] {'Binds': ['/dbfiles/test:/opt/db'], 'PortBindings': {'3001/tcp': [{'HostPort': '3000', 'HostIp': ''}], '2425/tcp': [{'HostPort': '2424', 'HostIp': ''}], '2481/tcp': [{'HostPort': '2480', 'HostIp': ''}]}}
docker ps 告诉我:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
169ad3ae0f63 test:test "./initdb.sh" 5 minutes ago Up 5 minutes 2424/tcp, 2480/tcp, 3000/tcp silly_pasteur
但是,如果我给它映射 3000 -> 3000、2424 -> 2424 和 2480 -> 2480 它给出
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cba483673bdd test:test "./initdb.sh" 53 minutes ago Up 5 minutes 0.0.0.0:2424->2424/tcp, 0.0.0.0:2480->2480/tcp, 0.0.0.0:3000->3000/tcp stupefied_ptolemy
关键是从命令行我可以使用正确的端口映射启动容器。那是
docker run -d -p 3001:3000 -p 2425:2424 -p 2481:2480 -v /dbfiles/test:/opt/db localhost:5000/test:test /initdb.sh
给出了想要的结果。
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7c1580e0ace9 localhost:5000/test:test "/initdb.sh" 8 seconds ago Up 6 seconds 0.0.0.0:2425->2424/tcp, 0.0.0.0:2481->2480/tcp, 0.0.0.0:3001->3000/tcp backstabbing_brahmagupta
但是使用 docker-py 我只是无法弄清楚如何将端口映射到不同的端口号。我错过了什么?