The Hotel Hero

Notes by a Sysadmin

Cluster | Philosophy | Stack

Mosquitto brocker - Docker Swarm Service

April 7, 2021 | Cluster

Setting a MQTT broker up on Swarm.

I have setup a nfs share that resides on each node and mounting is done on this share. In preparation I have have made the directories in the nfs-share that the bind is going to use.

The "stack" deployment file would look like this (usually you would probably run this like a service as there is only one service in this stack deployment), "docker-compose.yml":

version: "3.2"

    image: eclipse-mosquitto
      replicas: 1
      - type: bind
        source: /mnt/storage/mosquitto/data
        target: /mosquitto/data
      - type: bind
        source: /mnt/storage/mosquitto/log    
        target: /mosquitto/log
      - "/mnt/storage/mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf"
      - 1883:1883
      - 9001:9001

The "mosquitto.conf" file have to be created before deployment.

This is a simple example, we will change it later to add a small amount of security. Basically you might consider SSL/TLS encryption of traffic, but it comes with the cost of speed (so, depending on the information and network you have to make a qualified decision here).

The first "mosquitto.conf" will look like this:

allow_anonymous true
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log


Now, it's time to see if our service will deploy without errors. And then test it from a MQTT client.

docker stack deploy --compose-file docker-compose.yml stack-MQTT

(Now even thou everything seems to be running fine, I could not access as anonymous)

User and Authentication

Change the "mosquitto.conf", so it will look like the following:

allow_anonymous false
password_file /mosquitto/data/pwfile
listener 1883
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log

Create a file "pwfile" in the the data mount /mnt/storage/data:

touch pwfile
chmod 666 pwfile

Access the container: 

sudo docker exec -it stack-MQTT_mosquitto.1.3te1smzgws78giuaa11roqu3q sh

and execute the following line:

mosquitto_passwd -c /mosquitto/data/pwfile username

This will generate the "username" and prompt for a password that will be written as a hash to "pwfile".


I'm a Sysadmin, network manager and cyber security entusiast. The main purpose of this public "notebook" is for referencing repetitive tasks, but it might as well come in handy to others. Windows can not be supported! But all other OS compliant with the POSIX-standard can (with minor adjustments) apply the configs on the site. It is Mac OSX, RHEL and all the Fedora based distros and Debian based (several 100's of OS's), all the BSD distros, Solaris, AIX and HP-UX.