Search code examples
dockerdocker-composemqttmosquittodocker-network

Can't connect from Python Docker to mqtt Docker


So I've got a toke/mosquitto docker container running to which I can connect from outside docker.

Then I'm using a Python docker container that should publish data to my mosquitto broker. Here's my code:

import paho.mqtt.client as paho
import time
import random

broker = "localhost"
port = 1883


def on_publish(client, userdata, result):
    print("Device 1 : Data published.")
    pass

client = paho.Client("admin")
client.on_publish = on_publish
client.connect(broker, port)

for i in range(20):
    d = random.randint(1, 5)

    # telemetry to send
    message = "Device 1 : Data " + str(i)
    time.sleep(d)

    # publish message
    ret = client.publish("/data", message)

print("Stopped...")

The code works trying to connect to a mqtt broker not running in docker.

But I can't figure out how to let both run with docker and connect to each other. My error message is:

Traceback (most recent call last):
  File "./pub_client1.py", line 15, in <module>
    client.connect(broker, port)
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 937, in connect
    return self.reconnect()
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 1071, in reconnect
    sock = self._create_socket_connection()
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
    return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
  File "/usr/local/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/local/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
OSError: [Errno 99] Cannot assign requested address

Im already using a docker network. What am I missing?

Thanks already for the help :)


Solution

  • As mentioned by Felipe, localhost will not work when using docker. You must change broker = "localhost" to point to the service you defined on your docker compose file for mqtt or to the IP address of mqtt when running on different network.

    If your docker compose file references mqtt as mqtt (mqtt: build mqtt:latest) then you need to change your broker variable to broker = "mqtt"