Reputation: 141
I’m running Docker Version 17.06.2-ce-mac27 (19124) on mac osx. I’m trying to run a simple python server script using socket in a container and a client script in the container host. It seems like the client script can connect to the port but not trigger the server script.
When I run the client script from outside the container, I get an empty response:
port_test_server$ ./echo_client.py
Received ‘’
and there is no output from the server script running in the container.
when I run the client script from inside the container I get the expected response
port_test_server$ docker container exec 7c7d1fb7e614 ./echo_client.py
Received 'where there is love there is life'
and the expected output from the server script running in the container:
port_test_server$ docker run -it --expose 8887 -p 8887:8887 ptserver
Connected by ('127.0.0.1', 38694)
So the server script is running in the container, and the client script run from outside the container is connecting to the port, but it seems like the server script is not being trigerred.
Here is the code:
Docker file: (copies echo_client.py and echo_server.py in to 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
Server script 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()
Client script 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 command to run the container:
port_test_server$ docker run -it --expose 8887 -p 8887:8887 ptserver
Upvotes: 0
Views: 97
Reputation: 51836
One way to solve the issue is to start the container using a host network mode
docker run -it --expose 8887 -p 8887:8887 --network host ptserver
In that case, localhost will resolve to the host machine ip address.
Upvotes: 1