Hosting Mosquitto MQTT Broker on Docker Compose

Hosting Mosquitto MQTT Broker on Docker Compose
Hosting Mosquitto MQTT Broker on Docker Compose

I'm planning to build motion and contact sensors for my washroom that can automate the light switch. I will use a ESP32-C3 hook up to other sensors and MQTT to communicate with my Home Assistant.

Since I hosted my Home Assistant using Docker on Debian 11 with my Orange Pi Zero 3, I will also host my MQTT broker using Docker.

Prerequisite

Please make sure Docker Compose already installed on your system.

Prepare docker-compose.yaml

We need to create a folder, store and create the docker-compose.yaml in the folder. If you have a GUI system, you create both folder and docker-compose.yaml through the UI. Here I'm using terminal to create both folder and file.

First step, we create a folder. I named the folder as services.

$ mkdir services

Change the directory to services folder.

$ cd services

Create and open the docker-compose.yaml.

$ nano docker-compose.yaml

Paste the text below into docker-compose.yaml. Then, we save the docker-compose.yaml by CTRL + X and Enter keys.

version: "3.8"
services:
  mosquitto:
    container_name: mosquitto
    image: eclipse-mosquitto
    restart: always
    volumes:
      - ./config/mosquitto/conf:/mosquitto/config
      - ./config/mosquitto/data:/mosquitto/data
      - ./config/mosquitto/log:/mosquitto/log
    ports:
      - 1883:1883
      - 9001:9001
  • volumes Will mount 3 folders (conf, data, log) from the host to the container.
  • ports Will expose the container's 1883 and 9001 ports to host.

Authentication for Mosquitto MQTT Broker.

This step is optional, but recommended. We can use the Mosquitto's mosquitto_passwd tool to generate/manage password file.

 $ docker compose exec mosquitto mosquitto_passwd -c /mosquitto/config/password.txt admin NEWPASSWORD
  • You can replace these two arguments: admin and NEWPASSWORD. admin is the username and NEWPASSWORD is obviously the password.

Set up MQTT Configuration File.

We need to create a configuration file in our host ./config/mosquitto/conf folder.

listener 1883
listener 9001

allow_anonymous false
password_file /mosquitto/config/password.txt  

persistence true
persistence_location /mosquitto/data/

log_dest file /mosquitto/log/mosquitto.log
  • listener 1883 & listener 9001 - broker listen to port 1883 and 9001.
  • allow_anonymous false & password_file /mosquitto/config/password.txt - enable username and password authentication according to /mosquitto/config/password.txt setting.
  • persistence true & persistence_location /mosquitto/data/ - Enable broker to store file on disk and store to /mosquitto/data/mosquitto.db.
  • log_dest file /mosquitto/log/mosquitto.log - Store logs /mosquitto/log/mosquitto.log

Start the Mosquitto MQTT Broker container

The last step is bringing the container up.

$ docker-compose up -d
Next Post Previous Post
No Comment
Add Comment
comment url