Tutorials  /  Ubuntu

Install and Secure Mosquitto MQTT Broker on Ubuntu 20.04

Ccentron Redaktion · May 2025 ·8 min read ·Ubuntu, Tutorial

Mosquitto is a free and open-source message broker implementing the MQTT protocol, which stands for Message Queuing Telemetry Transport. It functions in alignment with the TCP/IP protocol suite and serves as a foundational communication platform for IoT (Internet of Things) systems.

Benefits of MQTT for Resource-Constrained Devices

Due to its exceptionally small footprint, MQTT is highly suitable for environments with limited device capabilities. The lightweight protocol makes it ideal for devices with restricted battery capacity, low network throughput, and inconsistent internet access.

VM

Matching infrastructure at centron

Ubuntu servers without your own hardware: ccloud³ VMs with full root access from €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

How Mosquitto Operates

Mosquitto works based on a publisher/subscriber architecture. In this setup, client devices establish a connection with the Mosquitto server, which operates as an intermediary (broker). It forwards messages from publishers to all clients that are subscribed to specific topics or channels.

Purpose of This Guide

This guide walks you through the process of setting up the MQTT Broker using Mosquitto on an Ubuntu 20.04 system. You will also learn how to configure Mosquitto to see how the event-based MQTT protocol facilitates communication in IoT ecosystems.

Prerequisites

To complete this tutorial, ensure you have the following:

  • A server running Ubuntu 20.04.
  • A user account with sudo privileges (not root).

How to Install Mosquitto on Ubuntu 20.04

To retrieve the Mosquitto package from Ubuntu’s software sources and install the MQTT broker, follow these essential steps. This process illustrates how Mosquitto can be installed on Ubuntu.

Begin by accessing your server through SSH and refreshing the list of available packages.

Console
$ sudo apt update

Now install the Mosquitto package using the command below:

Console
$ sudo apt install -y mosquitto

At this point, the Mosquitto package should be installed on your system. To check whether the Mosquitto service is running, execute the following command:

Console
$ sudo systemctl status mosquitto

Verify that the package is loaded and actively running. You should see output similar to the following:

YAML
● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker
     Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor pr>
     Active: active (running) since Fri 2021-10-08 06:29:25 UTC; 12s ago
       Docs: man:mosquitto.conf(5)
             man:mosquitto(8)

Once the Mosquitto service is active, you can manage it using the commands below.

To stop the Mosquitto service:

Console
$ sudo systemctl stop mosquitto

To start the Mosquitto service again:

Console
$ sudo systemctl start mosquitto

To restart the Mosquitto service:

Console
$ sudo systemctl restart mosquitto

Installing and Testing Mosquitto Clients on Ubuntu

MQTT clients establish connections to the Mosquitto broker in order to transmit and receive messages across different topics based on the specific use case. Each client can function as a publisher, subscriber, or both. To evaluate this capability, begin by installing the Mosquitto client on your Ubuntu system.

The Mosquitto package comes with a command-line utility that facilitates testing of server operations. Use the following command to install the client:

Console
$ sudo apt install -y mosquitto-clients

Once installed, subscribe to a specific topic. In MQTT, a topic is a string used by the broker to route messages to connected clients. For example, in a smart home system, common topic strings might include:

Code
home/lights/sitting_room
home/lights/kitchen
home/lights/master_bedroom
home/lights/kids_bedroom

To subscribe to one of these topics, use the mosquitto_sub -t command followed by the topic name. For instance, to listen on the home/lights/sitting_room channel, run:

Console
$ mosquitto_sub -t "home/lights/sitting_room"

This command runs in blocking mode, meaning your terminal session will stay open and listen for incoming messages.

Now, open a second terminal window while keeping the first one active. From the new terminal, send an ON message to the home/lights/sitting_room topic using this command:

Console
$ mosquitto_pub -m "ON" -t "home/lights/sitting_room"

You should see the message ON appear in the first terminal:

Code
ON

Next, send another message—this time OFF—to the same topic using the following command:

Console
$ mosquitto_pub -m "OFF" -t "home/lights/sitting_room"

The first terminal window should now display both messages:

Code
ON
OFF

In this walkthrough, you manually publish and subscribe to MQTT messages using Mosquitto clients. In practical deployments, this interaction is usually handled by microcontrollers capable of running TCP/IP stacks, such as the ESP8266. These devices send messages to brokers to control or observe equipment.

Real-World Applications of Mosquitto

  • Sending heartbeat data from patients to hospital servers for remote monitoring, helping avoid costly hospital visits.
  • Monitoring variables in the oil and gas sector, where thousands of sensors relay data via satellite to central systems. Due to limited bandwidth and high data costs, MQTT ensures data is sent only when needed.
  • Tracking train locations in the transportation sector, which allows central offices to offer more accurate scheduling information to travelers.
  • Acting as a middle layer in messaging platforms to update user statuses and facilitate direct communication.
  • Integrating with storage systems where clients forward messages to brokers, which then persist data in databases for long-term use.

In addition to these scenarios, there are many libraries available that let you connect to the Mosquitto broker from your preferred programming language—such as PHP, Python, Go, and others.

Securing the Mosquitto Server on Ubuntu

By default, Mosquitto does not enforce security mechanisms. To secure your server, you can configure it to require usernames and passwords for client connections.

Mosquitto loads its configuration files from the following directory:

Code
/etc/mosquitto/conf.d

Create a file named default.conf in that directory:

Console
$ sudo nano /etc/mosquitto/conf.d/default.conf

Insert the following directives to deny anonymous access and specify a password file location:

Code
allow_anonymous false
password_file /etc/mosquitto/passwd

Save and close the configuration file.

Open the password file using nano:

Console
$ sudo nano /etc/mosquitto/passwd

Add credentials for users who will connect to the Mosquitto broker. Replace the sample passwords with secure ones:

Code
john_doe:EXAMPLE_PASSWORD
mary_smith:EXAMPLE_PASSWORD_2

After saving, encrypt the passwords using the mosquitto_passwd utility:

Console
$ sudo mosquitto_passwd -U /etc/mosquitto/passwd

The passwords are now securely hashed, readable only by Mosquitto. Use the cat command to view the encrypted file contents:

Console
$ sudo cat /etc/mosquitto/passwd

You should see output like the following:

Code
john_doe:$6$TSzNycsj...5Qyvgd4g==
mary_smith:$6$DtlKf1lG.../rLHIL0Q==

Apply the changes by restarting the Mosquitto service:

Console
$ sudo systemctl restart mosquitto

From this point on, use the following syntax to authenticate while subscribing or publishing. Replace the username and password with your own:

Console
$ mosquitto_sub -u john_doe -P EXAMPLE_PASSWORD -t "home/lights/sitting_room"
$ mosquitto_pub -u john_doe -P EXAMPLE_PASSWORD -t "home/lights/sitting_room" -m "ON"

Any attempts to connect without valid credentials—or with incorrect ones—should now fail. For example:

Console
$ mosquitto_pub -m "ON" -t "home/lights/sitting_room"
$ mosquitto_sub -t "home/lights/sitting_room"
$ mosquitto_sub -u john_doe -P WRONG_PASSWORD -t "home/lights/sitting_room"
$ mosquitto_pub -u john_doe -P WRONG_PASSWORD -t "home/lights/sitting_room" -m "ON"

Expected output:

Code
...
Connection error: Connection Refused: not authorised.

Conclusion

This guide covered the installation of the MQTT Broker on Ubuntu 20.04 along with the Mosquitto server setup. You also learned how to publish and subscribe to messages using the command-line interface. Mosquitto is a strong candidate when deploying IoT solutions.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Ubuntu
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren