Skip to content

Instantly share code, notes, and snippets.

@ZiTAL
Created January 15, 2024 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZiTAL/1d8f2750a4940acf07f0774a5153eeaa to your computer and use it in GitHub Desktop.
Save ZiTAL/1d8f2750a4940acf07f0774a5153eeaa to your computer and use it in GitHub Desktop.
podman: Create a mosquitto server and connect from container's python script

MOSQUITTO SERVER

  1. install mosquitto
apt-get install mosquitto mosquitto-clients
  1. add config to create server
echo "allow_anonymous true"  >  /etc/mosquitto/conf.d/nework.conf
echo "listener 1883 0.0.0.0" >> /etc/mosquitto/conf.d/nework.conf
  1. restart mosquito daemon
/etc/init.d/mosquitto restart
  1. mosquitto subscribe: obtain messages
mosquitto_sub -t test --insecure
  1. mosquitto publish: send messages to subscriptors
mosquitto_pub -h localhost -t test -m "Hello, MQTT!"

PODMAN

  1. get my ip, in my case: 10.217.252.10
ip addr show
  1. create folder
mkdir -p /home/projects/pdm-python
cd /home/projects/pdm-python
  1. create script
nano index.py
import paho.mqtt.client as mqtt

print("Mosquito client:")

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(f"{msg.topic}: {msg.payload.decode()}")

client = mqtt.Client()

client.on_connect = on_connect
client.on_message = on_message

client.connect("10.217.252.83", 1883, 60)

client.loop_forever()
  1. build image
 podman build pdm-python .
  1. create network
podman network create localdomain
  1. run image
podman run --network=localdomain -ti pdm-python
  1. send message to mosquito server and check in the podman container
mosquitto_pub -h localhost -t test -m "Hello, MQTT!"
  1. podman container response:
test: Hello, MQTT!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment