主机客户端脚本从dockerized服务器脚本获取空string响应

我在mac osx上运行Docker版本17.06.2-ce-mac27(19124)。 我试图运行容器中的套接字和容器主机中的客户端脚本的简单的python服务器脚本。 看起来客户端脚本可以连接到端口但不触发服务器脚本。

当我从容器外部运行客户端脚本时,我得到一个空的响应:

port_test_server $ ./echo_client.py

收到''

并且容器中运行的服务器脚本没有输出。

当我从容器中运行客户端脚本时,我得到了预期的响应

port_test_server $ docker container exec 7c7d1fb7e614 ./echo_client.py

收到“有爱就有生命”

以及在容器中运行的服务器脚本的预期输出:

port_test_server $ docker run -it –expose 8887 -p 8887:8887 ptserver

由('127.0.0.1',38694)

因此,服务器脚本在容器中运行,而从容器外部运行的客户端脚本正在连接到端口,但似乎服务器脚本没有被触发。

这里是代码:

Docker文件:(将echo_client.py和echo_server.py拷贝到workdir中)

FROM debian:jessie-slim ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -y locales \ && localedef -i en_US -c -f UTF-8 en_US.UTF-8 ENV LANG en_US.utf8 RUN apt-get update && apt-get install -y libssl-dev libsnappy-dev python python-pip python-dev gcc git curl RUN easy_install --upgrade pip RUN mkdir /test_wd WORKDIR /test_wd COPY . /test_wd RUN chmod +x *.py RUN ls CMD ./echo_server.py 

服务器脚本echo_server.py:

 import socket HOST = localhost # Hostname to bind PORT = 8887 # Open non-privileged port 8888 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(10) while 1: conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() 

客户端脚本echo_client.py:

 import socket HOST = 'localhost' # Set the remote host, for testing it is localhost PORT = 8887 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('where there is love there is life') data = s.recv(1024) s.close() print 'Received', repr(data) 

Docker命令来运行容器:

port_test_server $ docker run -it –expose 8887 -p 8887:8887 ptserver

解决此问题的一种方法是使用主机networking模式启动容器

 docker run -it --expose 8887 -p 8887:8887 --network host ptserver 

在这种情况下,localhost将parsing为主机的ip地址。