A quick guide on how to install a MQTT Broker via Docker Compose

ℹ️
The content of this blog post was originally a 3-year-old GitHub gist. I decided it would probably be better if I transferred it to this blog, since I have many things on here already. Also, hopefully, it helps a few people on here.
Installing a MQTT Broker via Docker Compose
- Create a folder for the MQTT installation (e.g.
~/docker/mqtt
) - Create a
docker-compose.yml
file with the following content:
services:
mqtt:
container_name: mosquitto
image: eclipse-mosquitto:latest
restart: always
ports:
- "1883:1883"
- "9001:9001"
volumes:
- ./config:/mosquitto/config
- ./data:/mosquitto/data
- ./log:/mosquitto/log
- Run the container with
docker compose up -d
. - Create the
mosquitto.conf
file in theconfig
folder and fill it with the following content:
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
listener 1883
listener 9001
protocol websockets
If you don't want to add a user and disable anonymous logins, then you can just restart the container with docker compose restart
and you're good to go! 😄
Adding a user
- Run
docker compose exec -it mqtt sh
. - Add a new user with
mosquitto_passwd -c /mosquitto/config/mosquitto.passwd username
. (Replaceusername
with whatever you want as a username.) - Now you'll be asked to enter the password for that new user.
- Exit the container shell with
exit
. - Add the following content to the
mosquitto.conf
file:
password_file /mosquitto/config/mosquitto.passwd
allow_anonymous false
- Restart MQTT with
docker compose restart
and you're done! 🙂