A minimal MQTT pub/sub example: an EMQX broker in Docker, one publisher, one subscriber.
Running this locally? Read docs/RUNNING_LOCALLY.md. It covers prerequisites, configuration, verification, troubleshooting and cleanup in full. The quickstart below is the happy path only.
Requires Python 3.12+, Poetry 2.x, and Docker with Compose v2+.
# 1. Install dependencies. `poetry lock` is required first --- the committed lock file is stale.
poetry lock
poetry install --no-root
# 2. Spin up the broker (EMQX on port 1883, dashboard on 18083).
docker compose -f docker-compose.infrastructure.yaml up -d
# 3. Run the subscriber from the repo root. It runs until you stop it.
poetry run python subscriber.py
# 4. In a second terminal, also at the repo root, publish one message.
poetry run python publisher.py
# 5. Tear the broker down when you are done.
docker compose -f docker-compose.infrastructure.yaml downTwo things bite people here:
- Run the scripts from the repository root.
log.iniis loaded by relative path, so any other working directory fails withFileNotFoundError: log.ini doesn't exist. - Call Python explicitly. The scripts have no shebang and are not executable, so
poetry run ./subscriber.pyfails with[Errno 13] Permission denied.
mqtt-example/
├── publisher.py Publisher script that sends a message to an MQTT topic.
├── subscriber.py Subscriber script that listens to MQTT topics and logs messages.
├── log.ini Logging configuration file for both scripts. Must be in the working directory at runtime.
├── pyproject.toml Poetry project configuration file. Defines dependencies (paho-mqtt, etc.) and development tools (black, isort).
├── poetry.lock Locked dependency versions. Commit this to ensure reproducible environments.
├── docker-compose.infrastructure.yaml Docker Compose configuration that spins up an EMQX broker for local development.
├── docs/ Documentation directory.
│ └── RUNNING_LOCALLY.md Complete guide covering prerequisites, configuration, verification, troubleshooting and cleanup.
└── .gitignore Git ignore file.
The subscriber logs the topic and payload once the publisher runs:
[2026-11-28 22:10:46,318.318] [INFO] [subscriber.py:56]: Creating client: subscriber-local
[2026-11-28 22:10:46,318.318] [INFO] [subscriber.py:71]: Connecting to localhost:1883...
[2026-11-28 22:10:46,321.321] [INFO] [subscriber.py:15]: Connected with result code: Success
[2026-11-28 22:10:46,322.322] [INFO] [subscriber.py:43]: Subscribed with QoS: 1
[2026-11-28 22:10:52,407.407] [INFO] [subscriber.py:33]: some/cool/topic
[2026-11-28 22:10:52,407.407] [INFO] [subscriber.py:34]: b'{"hello": "world"}'
Linux and macOS:
pipx install poetry
poetry --versionWindows --- via Scoop and pipx:
pipx install poetry
poetry --versionThere is none to do, and no .env to create. Broker host, port and credentials are hardcoded
in subscriber.py and publisher.py. See
Configuration for the exact lines to edit.
poetry run isort .
poetry run black .