I've created 3 containers:
A container for publishing messages on MQTT protocol every second using python paho-mqtt
A subscriber container
A mosquitto server container
Container creation commands:
docker image build -t publisher /path/to/dockerfile folder
docker image build -t subscriber /path/to/dockerfile folder
Publisher container docker file:
FROM python:3.9.7
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
EXPOSE 1883
COPY . .
CMD [ "python", "app.py" ]
And this is mosquitto container log, that shows it runs properly:
1658502881: mosquitto version 2.0.14 running
1658502881: New connection from 172.17.0.5:53757 on port 1883.
1658502881: New client connected from 172.17.0.5:53757 as python-mqtt-29 (p2, c1, k60).
1658502881: New connection from 172.17.0.4:45437 on port 1883.
1658502881: New client connected from 172.17.0.4:45437 as python-mqtt-12 (p2, c1, k60).
Apparently, everything looks good but The problem is when I run the publisher and subscriber containers (docker run publisher
), the terminal app freezes up for about 2,3 minutes and then all the messages show up after that delay.
Again pub and sub containers freeze up for 2,3 minutes.
Could anyone help me with that?
Update:
My publisher app
import random
import time
from paho.mqtt import client as mqtt_client
broker = '172.17.0.3'
port = 1883
topic = "python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
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.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(1)
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
My subscriber:
import random
import pandas
from paho.mqtt import client as mqtt_client
broker = '172.17.0.3'
port = 1883
topic = "python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 100)}'
def connect_mqtt() -> mqtt_client:
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.on_connect = on_connect
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
client.subscribe(topic)
client.on_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
run()