Mosquitto brocker - Docker Swarm Service
April 7, 2021 | ClusterSetting 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"
services:
mosquitto:
image: eclipse-mosquitto
deploy:
replicas: 1
volumes:
- 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"
ports:
- 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
Deployment
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".