1

Basically I have a mosquitto broker running on the host on port 1883. Im deploying a python publish app on a docker container that should publish on the mosquitto broker on the host. Im using 172.17.0.1 to connect to the client so I though it should work, but I get connection refused.

How do I connect my docker container to my host mqtt broker?

This is my mqtt publish app, but it's working I think it's not relevant

import random
import time
from os import path
import sys
from pathlib import Path
import datetime
from paho.mqtt import client as mqtt_client



broker = '172.17.0.1'
port = 1883
topics = []
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = 'local'
password = 'localpw'
status_topic = []
status_m = 0
sensor_num_set = False


def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def publish(client):
    msg = "test"
    client.publish(msg, qos=0)
    print(f"Published")


def run():
    # node = Path('/.kubeedge_app_secrets/node.secret').read_text()
    client = connect_mqtt()
    client.loop_start()
    while True:
        publish(client)
        time.sleep(10)

if __name__ == '__main__':
    run()
5
  • 2
    172.17.0.1 isn't the IP-address of your host, is it? It looks like a Docker-internal IP-address. Commented Nov 18, 2022 at 12:10
  • Then the correct way would be accesing the host with it's private IP? Is it reachable from inside the container? Commented Nov 18, 2022 at 12:15
  • 1
    Seems easy enough to try ;D (but yes, that's how it works) Commented Nov 18, 2022 at 12:22
  • 2
    Most likely you have not changed the default config for mosquitto, which now defaults to only listening on 127.0.0.1/localhost which is why it is refusing connections. See link in closure notice. Once configured correctly, 172.17.0.1 should work as well Commented Nov 18, 2022 at 13:27
  • That's it! I knew it had to be 172.17.0.1 since that's docker host. Thank you so much! @hardillb Commented Nov 18, 2022 at 17:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.