ZMQ communication in python between a Docker Container and localhost using WSL and MacOS

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 . .


CMD [ "python", "./", "5546" ] :

import zmq
import time
import sys

port = "5546"
if len(sys.argv) > 1:
    port = sys.argv[1]

context = zmq.Context()
socket = context.socket(zmq.REP)
# socket.bind("tcp://*:%s" % port)
socket.bind("tcp://" % port)

while True:
    #  Wait for next request from client
    message = socket.recv()
    print("Received request: ", message)
    socket.send_string("World from %s" % port)

And the client file :

import zmq
import sys

port = "5546"
if len(sys.argv) > 1:
    port = sys.argv[1]

if len(sys.argv) > 2:
    port1 = sys.argv[2]

context = zmq.Context()
print("Connecting to server...")
socket = context.socket(zmq.REQ)
socket.connect("tcp://" % 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, "...")
    #  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:

But no message is either sent or received by the Docker container nor the localhost.

On Windows, when I do the following modifications :

  • Inside : 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 ?