Skip to main content
 首页 » 编程设计

python之docker remote api 无法将端口绑定(bind)到主机

2025年05月04日20insus

我试图使用 docker 的远程 api 来绑定(bind)主机,但它总是失败。

我使用 python 和 urllib2 传递这个 dict:

{ 
    'Tty':True, 
    'Volumes':[], 
    'Image':'ubuntu', 
    'Cmd':'', 
    'WorkingDir':None, 
    'Entrypoint':None, 
    'Env':None, 
    'AttachStdin':False, 
    'AttachStdout':True, 
    'AttachStderr':True, 
    'OpenStdin':True, 
    'ExposedPorts':{'80/tcp':{}}, 
    'HostConfig':{'PortBindings':{'80/tcp':['15080']}} 
} 

然后我使用远程 api 检查容器,它给了我以下信息:

"NetworkSettings":{ 
    "Bridge":"docker0", 
    "Gateway":"172.17.42.1", 
    "IPAddress":"172.17.0.48", 
    "IPPrefixLen":16, 
    "PortMapping":null, 
    "Ports":{"22/tcp":null,"80/tcp":null} 
} 

我也试过用这个链接里的方法Binding a port to a host interface using the REST API , 但是当我发布数据启动容器时,它会引发 HTTP 错误 500。所以我猜测是否更改了 docker remote api。

请您参考如下方法:

看起来您的 PortBindings 参数略有偏差。您缺少 "HostPort":

将其更改为:

'HostConfig':{'PortBindings':{'80/tcp':[{ "HostPort": '15080' }] }} 

来自docs :

  • PortBindings - A map of exposed container ports and the host port they should map to. It should be specified in the form { <port>/<protocol>: [{ "HostPort": "<port>" }] } Take note that port is specified as a string and not an integer value.