我有一个用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 btw上)
答案 0 :(得分:1)
您的问题是您运行容器并且不等待服务出现。你应该等待服务起来。您可以使用以下内容
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/