Docker容器无法连接到在本地主机上运行的服务器

我有一个运行服务器的python文件:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import json class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() def do_GET(self): self._set_headers() with open('files.json') as myfile: self.wfile.write(myfile.read()) .... def run(server_class=HTTPServer, handler_class=S, port=8080): server_address = ('', port) httpd = server_class(server_address, handler_class) print 'Starting httpd...' httpd.serve_forever() 

另外做一个获取请求:导入请求

 SESSION = requests.Session() SESSION.trust_env = False url = "http://localhost:8080" response = SESSION.get(url) data = response.json() 

这正常运行时正常工作。 但是,当我containerise应用程序(而不是服务器),请求引发这个错误在我身上:

 raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7ec03e5ed0>: Failed to establish a new connection: [Errno 111] Connection refused',)) 

我认为这是因为docker不知何故阻止我连接到本地主机上的服务器:8080?

感谢您的帮助☺

一个容器意味着是一个孤立的环境。 这是运行保护主机操作系统进程的“监狱”。 将容器看作具有自己的IP地址的虚拟机。 localhost将是试图连接到自己的容器。

我猜你可以使用其公共IP地址在主机上联系端口8080。

在Docker中运行服务器会更有意义。 然后,您可以将服务器容器中的端口映射到主机上的端口。 那么你的客户将按预期工作。

容器可以与主机os进行交互的两种最常见的方式是:

  • 将networking端口从容器映射到主机时
  • 将文件作为卷从主机映射到容器时

由于很好的原因,这是相当严格的。