Docker Community Forums

Share and learn in the Docker community.

Accessing app running in Docker container on macOS Big Sur host machine from other machine in local network

Hi experts,

I am running a Mosquitto broker for test purposes on a MacOS/Big Sur machine in a local network. The Docker system environment is:

  • Docker desktop version: 3.2.1 (61626)
  • The Mosquitto server I use is the standard Docker image from Docker Hub.

To start the container I used the command

docker run -it -p 1883:1883 eclipse-mosquitto mosquitto -c /mosquitto-no-auth.conf

Locally (on the Mac host, I can communicate with the server as expected. For example, executing the following Python script for the sender/producer:

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect("localhost", 1883, 60)
client.publish("topic/test", "Hello world!")
client.disconnect()

And the script for a listener/subscriber:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("topic/test")

def on_message(client, userdata, msg):
    if msg.payload.decode() == "Hello world!":
        print("Received HELLO WORLD!")
        client.disconnect()

client = mqtt.Client()
client.connect("localhost", 1883, 60)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()`

works fine.

However, I want to connect to the server in the container from a Windows machine in the same local network. This fails if I replace the “localhost” above with the IP of my Mac-machine, the container is not reachable.

How can I reach the container/mosquitto server from the Windows PC?

You cannot use --network=host on Mac to connect via host ports but binding to host port using -p options works.

I WANT TO CONNECT TO A CONTAINER FROM THE MAC

Port forwarding works for localhost; --publish, -p, or -P all work. Ports exposed from Linux are forwarded to the host.

Our current recommendation is to publish a port, or to connect from another container. This is what you need to do even on Linux if the container is on an overlay network, not a bridge network, as these are not routed.

For your use case,

You need to create a docker network and attach both the DB and application containers to this network. Then the containers will be able to talk to each other by their name. You can also publish the application container port so that you can access it from your host.

Instead of creating the network, attaching the containers to the network etc manually, you can use docker-compose.