gpt4 book ai didi

python - 为什么我无法在 python 中 ping docker 容器?

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:24 25 4
gpt4 key购买 nike

我有一个用 python docker 库制作的 docker 容器,如下所示:

docker_client.containers.run(docker_image, detach=True, ports={'80/tcp': 83})

我在 python 中启动它并随后运行测试请求:

r = requests.get("http://localhost:83")

我收到连接错误:

requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

发生这种情况时,应用程序退出,但 docker 容器仍在运行,因此我尝试运行 curl localhost:83 并且成功,没有问题。

这是怎么回事?(顺便说一句,这是在 macOS 上)

最佳答案

您的问题是您运行容器并且不等待服务启动。您应该等待服务启动。您可以使用如下所示的内容

def wait_net_service(server, port, timeout=None):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exception
"""
import socket
import errno

s = socket.socket()
if timeout:
from time import time as now
# time module is needed to calc timeout shared between two exceptions
end = now() + timeout

while True:
try:
if timeout:
next_timeout = end - now()
if next_timeout < 0:
return False
else:
s.settimeout(next_timeout)

s.connect((server, port))

except socket.timeout, err:
# this exception occurs only if timeout is set
if timeout:
return False

except socket.error, err:
# catch timeout exception from underlying network library
# this one is different from socket.timeout
if type(err.args) != tuple or err[0] != errno.ETIMEDOUT:
raise
else:
s.close()
return True

然后将您的代码更新为

docker_client.containers.run(docker_image, detach=True, ports={'80/tcp': 83})
wait_net_service("localhost", 83, 10)
r = requests.get("http://localhost:83")

PS:代码取自https://code.activestate.com/recipes/576655-wait-for-network-service-to-appear/

关于python - 为什么我无法在 python 中 ping docker 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48351418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com