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

An image showing the MQTT- and Docker Logo. In the corner there's a sticker of my dragon being happy.
(Sticker by @Ikaika)
ℹ️
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

  1. Create a folder for the MQTT installation (e.g. ~/docker/mqtt)
  2. 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
  1. Run the container with docker compose up -d.
  2. Create the mosquitto.conf file in the config 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

  1. Run docker compose exec -it mqtt sh.
  2. Add a new user with mosquitto_passwd -c /mosquitto/config/mosquitto.passwd username. (Replace username with whatever you want as a username.)
  3. Now you'll be asked to enter the password for that new user.
  4. Exit the container shell with exit.
  5. Add the following content to the mosquitto.conf file:
password_file /mosquitto/config/mosquitto.passwd
allow_anonymous false
  1. Restart MQTT with docker compose restart and you're done! 🙂