Skip to main content

Install MQTT Broker (Linux)

Mosquitto is a popular open-source MQTT broker. Here’s a step-by-step guide to installing and running Mosquitto on a Linux system.

Step 1: Install Mosquitto

For Debian-based systems (like Ubuntu):

  1. Update the package list:

    sudo apt-get update
  2. Install Mosquitto and its clients:

    sudo apt-get install -y mosquitto mosquitto-clients

Step 2: Set Up User and Password for MQTT Broker

  1. Create a password file for Mosquitto. This is where you choose your username. Make sure the path to the password file path is the same as set in the previous step.

    sudo mosquitto_passwd -c /etc/mosquitto/passwd yourusername
  2. Enter the password when prompted. After that you will have to confirm it by entering it a second time.

Step 3: Configure Mosquitto

Any files with extension .conf that are placed in /etc/mosquitto/conf.d/ will be used by the MQTT Broker.

  1. Add or open the configuration file in a text editor:

    sudo nano /etc/mosquitto/conf.d/mosquitto.conf
  2. Add these lines to configure the MQTT Broker to listen to port 1883 and require authentication.

    # If this is set to true then authentication is disabled.
    allow_anonymous false

    # Default is /etc/mosquitto/passwd, but any path could be used.
    password_file /etc/mosquitto/passwd

    # Another port can be used, but 1883 is default.
    listener 1883
    protocol mqtt

    listener 8080
    protocol websockets

    Press Ctrl + X to exit. It will ask you to save your changes.

    Press Y to save.

    It will ask you which file name to save to. It's already set to the current file, so just press Enter.

    Summary: The sequence of keystrokes to change your changes in nano text editor is Ctrl + X -> Y -> Enter.

Step 4: Start the Mosquitto Service

  1. Start the Mosquitto service:

    sudo systemctl start mosquitto
  2. Enable Mosquitto to start on boot:

    sudo systemctl enable mosquitto
  3. Check the status of the Mosquitto service:

    sudo systemctl status mosquitto

Step 5: Test the Mosquitto Broker

  1. Open a terminal and subscribe to a topic (e.g., test/topic):

    mosquitto_sub -h localhost -t test/topic -u "yourusername" -P "yourpassword"
  2. Open another terminal and publish a message to the same topic:

    mosquitto_pub -h localhost -t test/topic -m "Hello, MQTT" -u "yourusername" -P "yourpassword"

You should see the message "Hello, MQTT" appear in the terminal where you subscribed to the topic.

Additional Tips

  • Logging: Check the logs for any issues:

    sudo journalctl -u mosquitto

Congratulations! You have now installed, configured, and ran an MQTT broker using Mosquitto on your Linux system.