[How to] create a MQTT Docker container
Sergio Rius last edited by
I partially run my IoT implementation on docker. Today I was trying to test a mqtt broker inside docker. I always create my containers with permanent volumes and I maintain a separate folder for containers in my nas.
I installed all kinds of containers and pointing the storage to their config folder like
-v /mnt/docker-data/mqtt/config:/mosquitto/configalways worked. But mosquitto didn't want to run using remote volumes. Always complains about not being able to access the config file:
1565537402: Error: Unable to open config file /mosquitto/config/mosquitto.conf.
It doesn't matter if you try to change the owner of the folders or even give rwx to anyone.
After studying the project's dockerfile and folder structure I came to the conclusion that it's not prepared to be installed in one go, using persistent volumes (can be done in two execs). The project docker directions are not so clear and seem to be made for auto-consumption (like not providing a default configuration file)
So I made a small snippet to properly install and do a minimal configuration for the mosquitto container, pasted below.
# ./mqtt.sh /mnt/<thefolderwhereyoupersistdockervolumes>
#!/bin/bash VOLUME="$1" # Only if persistent volumes/configuration doesn't exist >>>>> if [ ! -d "$VOLUME"/mqtt ]; then mkdir -p $VOLUME/mqtt/config $VOLUME/mqtt/data $VOLUME/mqtt/log curl https://raw.githubusercontent.com/eclipse/mosquitto/master/mosquitto.conf -o $VOLUME/mqtt/config/mosquitto.conf cat <<EOT >> $VOLUME/mqtt/config/mosquitto.conf persistence true persistence_location /mosquitto/data/ log_dest file /mosquitto/log/mosquitto.log EOT chown -R 1883:1883 $VOLUME/mqtt fi docker run --name mqtt --restart=unless-stopped \ -p 1883:1883 \ -p 9001:9001 \ -v $VOLUME/mqtt/config/mosquitto.conf:/mosquitto/config/mosquitto.conf:ro \ -v $VOLUME/mqtt/data:/mosquitto/data \ -v $VOLUME/mqtt/log:/mosquitto/log \ -v /etc/localtime:/etc/localtime:ro \ -d eclipse-mosquitto docker exec -it mqtt mosquitto_passwd -c /mosquitto/config/pwfile iot # Add to a shared network between iot containers. (Node-Red, InfluxDb...) docker network create iot docker network connect iot mqtt
Notes: This snippet is stupid. It doesn't care what he gets as parameter, for example. So be smart when using it. And remember not adding the name of the container to the route. He always adds and assumes "mqtt"
/mnt/docker-data/mqttso take into account if you already have that folder.