I want to implement a zmq communication between a docker container and the localhost of my windows / mac computer. I want both the docker container and the localhost to be able to send and receive messages.
On linux, the following files enable the communication to work but not on Windows (WSL) / Mac :
Dockerfile :
FROM python:3.7
COPY requirements.txt ./
# COPY ./Received_Pictures ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5546
CMD [ "python", "./reqrep_server.py", "5546" ]
reqrep_server.py :
import zmq
import time
import sys
port = "5546"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
context = zmq.Context()
socket = context.socket(zmq.REP)
# socket.bind("tcp://*:%s" % port)
socket.bind("tcp://127.0.0.1:%s" % port)
while True:
# Wait for next request from client
message = socket.recv()
print("Received request: ", message)
time.sleep(1)
socket.send_string("World from %s" % port)
And the client file client.py :
import zmq
import sys
port = "5546"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
if len(sys.argv) > 2:
port1 = sys.argv[2]
int(port1)
context = zmq.Context()
print("Connecting to server...")
socket = context.socket(zmq.REQ)
socket.connect("tcp://127.0.0.1:%s" % port)
if len(sys.argv) > 2:
socket.connect("tcp://localhost:%s" % port1)
# Do 10 requests, waiting each time for a response
for request in range(1, 10):
print("Sending request ", request, "...")
socket.send_string("Hello")
# Get the reply.
message = socket.recv()
print("Received reply ", request, "[", message, "]")
Then I run the following commands :
docker build -t server . --network=host
docker container run --network=host server
And in another terminal:
python client.py
But no message is either sent or received by the Docker container nor the localhost.
On Windows, when I do the following modifications :
- Inside reqrep_server.py :
socket.connect (" tcp:// *:%s" % port)
- When building the docker container : I remove the “–host=network” flag then I run
docker container run -p 5546:5546 server
.
It works but only in one direction : the docker container sending to the localhost but not in the other direction, the docker container does not receive the “Hello” message but is able to send “World from …”.
Do you have any idea why it doesn’t work ?