Mosquitto is a message broker that implements the MQTT protocol. Mosquitto is an open-source project developed by Eclipse. MQTT protocol uses a publishing/subscribe model. A client can publish a message to a broker, and other clients can subscribe to the topic of that message. A broker is a central component that receives all messages from the clients and then publishes the messages to all subscribed clients.
This tutorial explains how to install Mosquitto broker inside a Docker container in the Linux. Commands have been tested on Ubuntu.
Prepare environment
Make sure you have installed Docker in your system. If you are using Ubuntu, installation instructions can be found in the post.
Install Mosquitto
Create directory to store Mosquitto configuration files:
sudo mkdir -p /opt/mosquitto/config
Create password file which contains default username admin
and password admin
:
echo 'admin:$7$101$e9hDhhPIAjJiABfM$ZAnMvDQF1kJKbndoVjKQLko8lvmP20ntiAbTSDrgLTyOLTF5TvRiJZ2EsjGasumP+22RO++iYdQDHhprPdHTug==' | sudo tee /opt/mosquitto/config/password_file
Create Mosquitto configuration file:
sudo nano /opt/mosquitto/config/mosquitto.conf
Once the file is opened, add the following content:
listener 1883
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
password_file /mosquitto/config/password_file
- Host network
Run the following command to create a container for Mosquitto that uses host network:
docker run -d --name=mosquitto --restart=always --network=host \
-v /opt/mosquitto/data:/mosquitto/data \
-v /opt/mosquitto/log:/mosquitto/log \
-v /opt/mosquitto/config:/mosquitto/config \
eclipse-mosquitto
- User-defined bridge network
User-defined bridge network can be used for listening on different port. By default, Mosquitto service is listening on port 1883. It can be changed with -p
option.
docker network create app-net
docker run -d --name=mosquitto --restart=always --network=app-net \
-p 8080:1883 \
-v /opt/mosquitto/data:/mosquitto/data \
-v /opt/mosquitto/log:/mosquitto/log \
-v /opt/mosquitto/config:/mosquitto/config \
eclipse-mosquitto
Once the container is started, the following command can be used to change user password:
docker exec -it mosquitto mosquitto_passwd -b /mosquitto/config/password_file admin pwd123
To apply changes, restart container:
docker restart mosquitto
Testing Mosquitto
To test Mosquitto broker, use the MQTT client mosquitto_pub
to publish a message on a specified topic:
docker exec -it mosquitto mosquitto_pub -u admin -P pwd123 -t 'test/topic' -m 'Test'
Uninstall Mosquitto
To completely remove Mosquitto, remove its container:
docker rm --force mosquitto
Remove Mosquitto image:
docker rmi eclipse-mosquitto
You can also remove Mosquitto data, logs and configuration files:
sudo rm -rf /opt/mosquitto
If a user-defined bridge network was created, you can delete it as follows:
docker network rm app-net
Leave a Comment
Cancel reply