Install Mosquitto 2 Broker on Ubuntu 20.04

Mosquitto is a message broker that implements the MQTT protocol. Mosquitto is an open-source project developed by Eclipse. MQTT protocol uses a publish/subscribe model. Client can publish 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 2 broker on Ubuntu 20.04.

Install Mosquitto

Add the Mosquitto repository:

sudo add-apt-repository -y ppa:mosquitto-dev/mosquitto-ppa

Run the following command to install Mosquitto broker:

sudo apt install -y mosquitto

Once installation is completed, we can check Mosquitto version:

mosquitto -h | grep version

You can execute the following command to determine if Mosquitto service is running:

sudo service mosquitto status

Also you can stop, start and restart service:

sudo service mosquitto stop
sudo service mosquitto start
sudo service mosquitto restart

Configure Mosquitto

Since Mosquitto 2, we must to configure authentication for Mosquitto broker before clients can connect. It can be configured to require username and password when client connects to the broker.

Password file can be created using mosquitto_passwd tool. First argument is path to a file, second argument is username. The -c option means that new password file will be created. Run the following command and enter a password for the user:

sudo mosquitto_passwd -c /etc/mosquitto/password_file myuser

Next, open Mosquitto configuration file:

sudo nano /etc/mosquitto/mosquitto.conf

Add the following lines at the end of a file:

listener 1883
password_file /etc/mosquitto/password_file

Restart Mosquitto service:

sudo service mosquitto restart

Testing Mosquitto

MQTT Explorer can be used for testing. It is a cross-platform MQTT client which can be installed as Desktop application. It can be downloaded from official website.

Get the IP address of your machine:

hostname -I

Next, open MQTT Explorer and provide details about MQTT connection. Enter the connection name, IP address, username and password. By default, Mosquitto broker is running on 1883 port. Click “SAVE” and then “CONNECT”.

Use MQTT Explorer to connect to Mosquitto broker on Ubuntu

If connection was successfully established, you will see a window like this:

MQTT Explorer main window

Uninstall Mosquitto

If you decided to completely remove Mosquitto and related dependencies, execute the following command:

sudo apt purge --autoremove -y mosquitto

Remove GPG key and repository:

sudo rm -rf /etc/apt/trusted.gpg.d/mosquitto-dev_ubuntu_mosquitto-ppa.gpg
sudo rm -rf /etc/apt/sources.list.d/mosquitto-dev-ubuntu-mosquitto-ppa-focal.list

You can also remove Mosquitto configuration:

sudo rm -rf /etc/mosquitto

Leave a Comment

Your email address will not be published. Required fields are marked *