Install Mosquitto MQTT Broker on Raspberry Pi

This tutorial shows how to install the Mosquitto Broker for MQTT communication on a Raspberry Pi board.

Install Mosquitto MQTT Broker on Raspberry Pi

Updated 10 June 2022

You can also run Mosquitto MQTT broker in the cloud. Running the MQTT Mosquitto Broker in the cloud allows you to connect several ESP32/ESP8266 boards and other IoT devices from anywhere using different networks as long as they have an Internet connection. Check the tutorial below:

What is an MQTT Broker?

MQTT stands for Message Queuing Telemetry Transport. MQTT is a simple messaging protocol, designed for constrained devices with low bandwidth. So, it’s the perfect solution to exchange data between multiple IoT devices.

MQTT communication works as a publish and subscribe system. Devices publish messages on a specific topic. All devices that are subscribed to that topic receive the message.

The MQTT broker is responsible for receiving all messages, filtering the messages, deciding who is interested in them, and then publishing the message to all subscribed clients.

mqtt-broker

There are several brokers you can use. In home automation projects, we use the Mosquitto Broker installed on a Raspberry Pi.

You can also install the Mosquitto broker on your PC (which is not as convenient as using a Raspberry Pi board, because you have to keep your computer running all the time to keep the MQTT connection between your devices alive).

For a more detailed explanation of MQTT communication, check out this article: What is MQTT and How It Works

Prerequisites

Before continuing with this tutorial

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

If you like home automation and you want to build a complete home automation system, I recommend downloading my home automation course.

Installing Mosquitto Broker on Raspberry Pi OS

After having your Raspberry Pi board prepared with Raspberry Pi OS, you can continue with this tutorial. 

Let’s install the Mosquitto Broker.

1) Open a new Raspberry Pi terminal window. If you’re running your Raspberry Pi headless, check this tutorial to learn how to establish an SSH connection between your computer and the Raspberry Pi.

2) Run the following command to upgrade and update your system:

sudo apt update && sudo apt upgrade

3) Press Y and Enter. It will take some time to update and upgrade (in my case, it took approximately 10 minutes).

4) To install the Mosquitto Broker enter these next commands:

sudo apt install -y mosquitto mosquitto-clients

5) To make Mosquitto auto start when the Raspberry Pi boots, you need to run the following command (this means that the Mosquitto broker will automatically start when the Raspberry Pi starts):

sudo systemctl enable mosquitto.service

6) Now, test the installation by running the following command:

mosquitto -v

This returns the Mosquitto version that is currently running in your Raspberry Pi. It will be 2.0.11 or above.

Installing Mosquitto MQTT broker Raspberry Pi

It will prompt the following message: “Starting in local only mode. Connections will only be possible from clients running on this machine. Create a configuration file which defines a listener to allow remote access.”

This means that by default, you can’t communicate with the Mosquitto broker from another device (other than your Raspberry Pi). This is applicable for Mosquitto version 2. More information about this topic on the Mosquitto documentation.

In Mosquitto 2.0 and up, you must choose your authentication options explicitly before clients can connect. In earlier versions, the default is to allow clients to connect without authentication.

Enable Remote Access/ Authentication

To enable remote access so that we can communicate with other IoT devices, we need to edit/create a configuration file.

In this tutorial, we’ll cover:

Choose the section that is more suitable for your scenario. We also recommend taking a look at the documentation for more details.

Mosquitto Broker Enable Remote Access (No Authentication)

1) Run the following command to open the mosquitto.conf file.

sudo nano /etc/mosquitto/mosquitto.conf

2) Move to the end of the file using the arrow keys and paste the following two lines:

listener 1883
allow_anonymous true
Mosquitto configuration file to allow remote connections and anonymous users

 
3) Then, press CTRL-X to exit and save the file. Press Y and Enter.
 
4) Restart Mosquitto for the changes to take effect.

sudo systemctl restart mosquitto

Mosquitto Broker Enable Remote Access (Authentication: user and password)

You can add a user/password authentication to your MQTT broker.

1) Run the following command, but replace YOUR_USERNAME with the username you want to use:

sudo mosquitto_passwd -c /etc/mosquitto/passwd YOUR_USERNAME

I’ll be using the MQTT user sara, so I run the command as follows:

sudo mosquitto_passwd -c /etc/mosquitto/passwd sara

When you run the preceding command with the desired username, you’ll be asked to enter a password. No characters will be displayed while you enter the password. Enter the password and memorize the user/pass combination, you’ll need it later in your projects to make a connection with the broker.

This previous command creates a password file called passwd on the /etc/mosquitto directory.

Now, we need to edit the mosquitto configuration file so that it only allows authentication with the username and password we’ve defined.

2) Run the following command to edit the configuration file:

sudo nano /etc/mosquitto/mosquitto.conf

3) Add the following line at the top of the file (make sure it is at the top of the file, otherwise it won’t work):

per_listener_settings true

4) Add the following three lines to allow connection for authenticated users and tell Mosquitto where the username/password file is located.

allow_anonymous false
listener 1883
password_file /etc/mosquitto/passwd

Your configuration file will look as follows (the new lines are in bold):

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

per_listener_settings true

pid_file /run/mosquitto/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d
allow_anonymous false 
listener 1883  
password_file /etc/mosquitto/passwd
Mosquitto broker configuration file authentication user pass

5) Press CTRL-X, then Y, and finally press Enter to exit and save the changes.

6) Restart Mosquitto for the changes to take effect.

sudo systemctl restart mosquitto

To check if Mosquitto is actually running, you can run the following command:

sudo systemctl status mosquitto

Now, you have authentication with username and password enabled. Remember that everytime you want to communicate with the broker, you’ll need to provide the username and password.

Add More Users/Change Password

To add more users to an existing password file, or to change the password for an existing user, leave out the -c argument:

mosquitto_passwd <password file> <username>

For example, if I want to change the password for the sara user and taking into account that the password file we created was called passwd, the command will be as follows:

sudo mosquitto_passwd /etc/mosquitto/passwd sara

Raspberry Pi IP Address

To use Mosquitto broker later in your projects, you’ll need to know the Raspberry Pi IP address. To retrieve your Raspberry Pi IP address, type the next command in your Pi Terminal window:

hostname -I

In our case, the Raspberry Pi IP address is 192.168.1.144. Save your Raspberry Pi IP address because you’ll need it in future projects.

Testing Mosquitto Broker and MQTT Client

After installing the Mosquitto broker, you should test your installation. You can follow the next tutorial:

Wrapping Up

An MQTT broker is essential if you want to use the MQTT protocol in IoT projects. The MQTT broker receives all MQTT messages and forwards them to all subscribed clients. In this tutorial, you’ve learned how to install the Mosquitto broker on a Raspberry Pi.

Like home automation? Learn more about Node-RED, Raspberry Pi, ESP8266, and Arduino with my course: Build a Home Automation System for $100.

Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing to my blog.

Updated June 10, 2022



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

96 thoughts on “Install Mosquitto MQTT Broker on Raspberry Pi”

  1. One of the best and clear tutorial I ever seen.
    I will be very much appreciated if you upgrade this tutorial to setup Mosquito server running on Raspberry Pi with TLS security connection and CA key(port 8883).
    Everything else is compromise. Specially when the raspberry is open to the Wide WEB.
    There is a lot post about that, but I did`t find good enough to work out of the box.
    Thank you and keep going
    Rosen

    Reply
  2. Hi Rui, I’m getting “1494513510: Error: Address already in use” message al of a sudden, it was all running ok, any help on what’s happening….thank you!

    Reply
  3. Hi Rui,

    Thanks. I found my mistake, it was the mqtt server ip that was not updated right in esp8266 client side code. Thanks for your tutorial (got some time for myself to follow your home automation course book).

    Reply
  4. This doesn’t seem to work with Stretch. Is there an update to this instruction set? “The following packages have unmet dependencies: . . .”

    Reply
    • These instructions work.
      I followed this installation procedure three weeks ago and it worked on a fresh installation with the latest Raspbian lite (Stretch).
      Did you upgrade your OS or followed someone else’s instructions before?

      You might have the Mosquitto software repositories outdated, which results in that exact problem. (You need to remove the repositories)
      Starting with a new installation and only following these instructions should install Mosquitto successfully.
      I hope this helps.

      Reply
  5. I greet you dear “program” friends and thank you for your effort to help. This “introductory” project worked with “RPi3B” and with “Buster” without any problems.
    But I have another problem. The problem with the initiating WiFi on RasPi3B + V. 2017 and Buster. I have 2pcs RPi3B with the installed Buster, WiFi without problems, RPi4B 4GB also without problems, just “with heating”. And in RPi3B +, we don’t even define our country “Slovakia”, but no other. I have already passed the whole internet and tried everything possible.

    Reply
  6. Thank you for your interest. Everything is working. “Mea culpa”. Mosquitto worked on the apparently, perfect.

    Reply
  7. On page 430, what’s the voltage on the breadboard for the DS18B20? The graphic doesn’t show the GND or V+ connection. I’m assuming 5v, since that’s usually what it takes to drive the sensor.

    Reply
  8. Hi Sara, on a Raspberry 4 with 4gb when entering the command ‘sudo systemctl enable mosquitto.service’ when pressing Enter it says’ Failed to enable unit: Unit file mosquitto.service does not exist. What could be the problem? Thank you

    Reply
  9. Hi, I need some help in building a salt water station that will measure temperature, electrical conductivity and dissolved oxygen. These three sensors will be hooked up on a tentacle t3 and on a raspberry pi 4b. I have scripts to read the data but I want somehow to have real time access to these data through a pc or a smartphone and not in the same network. Any ideas? Im newbie in Iot

    Reply
  10. What if my devices isn’t on the same network as my Raspberry Pi? How can I use my Raspberry Public IP address as a server?

    Reply
      • Certainly! If your Pi is reachable from outside of your local network, you can use the public IP address of your router. In the router’s settings make sure to route port numer 1883 to the appropriate address of the MQTT boker. Also make sure that your broker is password protected with a complex password becuause your firewall now has a hole in it.
        rgds
        Chris

        Reply
  11. Hi Rui,
    Even though it says,
    8) Move to the end of the file using the arrow keys and paste the following two lines:
    The file opened is blank and has no lines as shown in your screenshot. Any mistakes I have done before?
    Also which shortcut keys that I have to use when copying ‘listener 1883’ from this website and to paste it to file?

    Reply
  12. Well darn. I did a clean installation of Raspberry OS and then followed the instructions for installing mosquito exactly. Edited the mosquitto.conf and pasted in:
    listener 1883
    allow_anonymous true

    If I do mosquito -v after a reboot I still get:
    1639720453: mosquitto version 2.0.11 starting
    1639720453: Using default config.
    1639720453: Starting in local only mode. Connections will only be possible from clients running on this machine.
    1639720453: Create a configuration file which defines a listener to allow remote access.
    1639720453: For more details see https://mosquitto.org/documentation/authentication-methods/
    1639720453: Opening ipv4 listen socket on port 1883.
    1639720453: Opening ipv6 listen socket on port 1883.
    1639720453: mosquitto version 2.0.11 running

    I thought perhaps the listen socket was good news, but when I run the esp32 project I built from your tutorial it still shows
    connecting to MQTT
    disconnecting from MQTT

    I think for some reason Mosquitto is not reading that config file.

    Reply
    • Hi.
      Are you sure the changes made to the mosquitto.conf file were saved?
      After making the changes, you need to reboot your Raspberry Pi.
      Regards,
      Sara

      Reply
      • Sadly, yes, and I rebooted. In fact I unplugged everything last night because we had a storm lost power. Here’s a grab of the contents of /etc/mosquitto/mosquitto.conf:

        Place your local configuration in /etc/mosquitto/conf.d/

        #

        A full description of the configuration file is at

        /usr/share/doc/mosquitto/examples/mosquitto.conf.example

        pid_file /run/mosquitto/mosquitto.pid

        persistence true
        persistence_location /var/lib/mosquitto/

        log_dest file /var/log/mosquitto/mosquitto.log

        include_dir /etc/mosquitto/conf.d
        listener 1883
        allow_anonymous true

        The only odd thing I’ve noticed so far is that when I opened the mosquitto.conf file it still had my original changes in it. I didn’t reformat the mini-sd card, but the raspberry pi imager installation claimed all the original data would be lost. Apparently, that’s not entirely true.

        Reply
  13. Well, I have MQTT working, though I’m not entirely sure why. Looking around in stack overflow I reread this post: https://stackoverflow.com/questions/65278648/mosquitto-starting-in-local-only-mode

    And decided to try: $ mosquitto -v -c /etc/mosquitto/mosquitto.conf
    which yielded:
    1639763140: Error: Unable to write pid file.
    Which sort of confirms my concern that mosquitto is not usually reading the /etc/mosquitto/mosquitto.conf file.

    So I tried: sudo mosquitto -v -c /etc/mosquitto/mosquitto.conf
    Which doesn’t yield any messages at all. I checked to see if the tutorial app can actually connect to MQTT and it does! Yay. sort of. Of course, this means Mosquitto is not started as a usable service when the system boots. Perhaps you folks could figure out how to make that happen. I’d be happy about all this if I thought I knew what I was learning something, but I’m basically just trying stuff.

    Reply
      • It isn’t working the way your tutorials and the fixes I found on the web said it should. That’s a problem because I understand your tutorials (which is the entire point of doing them) but I don’t understand this random forced solution. But yes, it’s working. I did the MQTT testing tutorial as well, and that worked properly.

        Reply
        • Hi Bill.
          Thanks for the clarification.
          That fix is because, with version 2.0, by default, Mosquitto only allows connections from the local host for security reasons.
          Those lines we add to the configuration file allow us to connect any device on the local network to the broker.
          If you want to learn more about that subject, you can check the Mosquitto 2.0 vs 1.0 documentation: https://mosquitto.org/documentation/migrating-to-2-0/
          It is explained in greater detail there.
          I hope this helps.
          Regards,
          Sara

          Reply
  14. I’ve got the same issue as Bill Babcock, but I can’t seem to get sorted out on the pid file.

    I’m using a RPi4 with Raspian Buster

    From the terminal:
    pi@raspberrypi:~ $ mosquitto -v -c /etc/mosquitto/mosquitto.conf
    1641239054: Loading config file /etc/mosquitto/conf.d/custom.conf

    1641239054: Error: Unable to write pid file.

    If I run it without the config file, it starts fine:

    pi@raspberrypi:~ $ mosquitto
    1641239158: mosquitto version 2.0.12 starting
    1641239158: Using default config.
    1641239158: Starting in local only mode. Connections will only be possible from clients running on this machine.
    1641239158: Create a configuration file which defines a listener to allow remote access.
    1641239158: For more details see https://mosquitto.org/documentation/authentication-methods/
    1641239158: Opening ipv4 listen socket on port 1883.
    1641239158: Opening ipv6 listen socket on port 1883.
    1641239158: mosquitto version 2.0.12 running

    1641239161: New connection from ::1:46566 on port 1883.

    Just wanted to post this here to see if anyone else is having the same issue and were able to resolve it. Even as sudo I can’t cd into the directory with the pid files.

    In my config file I just have the standard
    listener 1883 0.0.0.0
    allow_anonymous true

    Any tips advice would love to hear it.

    Reply
  15. can I install MQTT broker on pi zero 2 W ?
    I try it without succes, I first run the apt update && apt upgrade command, but after download over 1GB of date, 7 minutes or so, it restart or something because there was no signal on hdmi out, the on board led seems to indicate some work, but after 1 hour there was still no signal on hdmi.
    So my quastion remains, is pi zero 2 w good for this article, or do I need a pi3 or 4 ?

    Reply
      • Hi Sara
        I succesed to install MQTT. I had problems when I give upgrade command, allways freez, sd coruption etc. When I did just update command before mqrr install, was ok.

        Reply
  16. I just installed Ubuntu on a PC that will be dedicated for running Node-red.
    I tried a few of the tutorials and find I cannot get my ESP8266 to send to Node-Red.

    my wish-list would be a simple ‘Hello-World’ with serial.print lines as to the success/failure of each step.

    In node-red, I get connecting next to my nodes, but nothing on the dashboard.

    I am using Mosquitto 1.6.9
    it seems that is the version for Ubuntu
    there is no configuration file and it appears (I am a noob so I don’t really know) that V2 of mosquitto defaulted to “this computer only” and you had to tell it to accept from other sources. i assume that means 1.6.9 did not need to have the mosquitto.config file.

    this tutorial:
    https://RandomNerdTutorials.com/esp8266-nodemcu-mqtt-publish-ds18b20-arduino/
    yields :
    Connecting to MQTT…
    Disconnected from MQTT.
    Connecting to MQTT…
    Disconnected from MQT

    this tutorial :
    https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/
    yields :
    Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
    Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
    Attempting MQTT connection…failed, rc=-2 try again in 5 seconds

    when I start Node-Red in Ubuntu, I get

    [mqtt-broker:7a5ee377caccc1ec] connection failed to broker : mqtt”//localhost:1883
    ( I hand typed as I am on my may computer reading from the screen of my dedicated PC)

    it seems I am having problems with network or linking or the broker…..
    can you point me towards the basics ?

    Reply
      • iot@emon:~$ mosquitto
        [ 49.566528]~DLT~ 2068~INFO ~FIFO /tmp/dlt cannot be opened. Retrying later…
        1650669434: mosquitto version 1.6.9 starting
        1650669434: Using default config.
        1650669434: Opening ipv4 listen socket on port 1883.
        1650669434: Error: Address already in use
        [ 59.582398]~DLT~ 2068~WARNING ~Lost log messages in user buffer when exiting: 6

        ======================

        iot@emon:~$ node-red
        22 Apr 19:18:05 – [info]

        Welcome to Node-RED

        22 Apr 19:18:05 – [info] Node-RED version: v2.2.2
        22 Apr 19:18:05 – [info] Node.js version: v14.19.1
        22 Apr 19:18:05 – [info] Linux 5.13.0-40-generic x64 LE
        22 Apr 19:18:05 – [info] Loading palette nodes
        22 Apr 19:18:07 – [info] Dashboard version 3.1.6 started at /ui
        22 Apr 19:18:08 – [warn] rpi-gpio : Raspberry Pi specific node set inactive
        22 Apr 19:18:08 – [info] Settings file : /home/iot/.node-red/settings.js
        22 Apr 19:18:08 – [info] Context store : ‘default’ [module=memory]
        22 Apr 19:18:08 – [info] User directory : /home/iot/.node-red
        22 Apr 19:18:08 – [warn] Projects disabled : editorTheme.projects.enabled=false
        22 Apr 19:18:08 – [info] Flows file : /home/iot/.node-red/flows.json
        22 Apr 19:18:08 – [info] Server now running at http://127.0.0.1:1880/
        22 Apr 19:18:08 – [info] Starting flows
        22 Apr 19:18:08 – [info] Started flows
        22 Apr 19:18:08 – [info] [mqtt-broker:7a5ee377caccc1ec] Connection failed to broker: mqtt://localhost:1883
        22 Apr 19:18:23 – [info] [mqtt-broker:7a5ee377caccc1ec] Connection failed to broker: mqtt://localhost:1883

        Reply
  17. Very helpful page, thank you.
    Finally I managed to access my RasPI remotely by adding two lines to the mosquitto.conf file.

    Reply
  18. Hi Guys!
    I’m following along and got everything working up until the client 2. The code compiles and loads OK, but I get the following output from the serial port, continuously repeating. The display is lit, but blank. Can you please help me troubleshoot this error?

    ————— CUT HERE FOR EXCEPTION DECODER —————

    Exception (0):
    epc1=0x40205dc9 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

    stack>>>

    ctx: cont
    sp: 3ffffdc0 end: 3fffffc0 offset: 0190
    3fffff50: 3ffe85cc 3ffee704 00000001 40205dc9
    3fffff60: 3fffdad0 3ffee704 3ffeea80 40205e18
    3fffff70: 3fffdad0 3ffee704 3ffeea80 4020134c
    3fffff80: feefeffe feefeffe feefeffe feefeffe
    3fffff90: feefeffe feefeffe feefeffe feefeffe
    3fffffa0: 3fffdad0 00000000 3ffeebac 40206f1c
    3fffffb0: feefeffe feefeffe 3ffe85e4 40100c99
    <<<stack<<<

    I’ve checked and double-checked all the code and it looks OK.
    It’s a NodeMCU, and I’m using the code downloaded from Github.

    Thanks!

    Reply
  19. Hello.
    Thank you for the perfect tutorial. Everything works perfectly on 3B+ with SSD mSATA, OS Raspberry Pi 64. The mosquito “settled” on the disk :).
    One observation: It is good when sometimes a person makes a mistake, just not often :), he learns a lot.

    Reply
  20. Hello.
    I have a problem in ThonnyIDE “break up” software with MQTT, ESP8266, broker RasPi3B+ and Enable Remote Access/ Authentication. I followed the Mosquitto Broker Enable Remote Access (Authentication: user and password) version. In the libraries “umqttsimle.py” and “main.py”, I changed the user and password. Here’s “umqttsimple.py”:
    def init(self, client_id, server, port=0, user=zzzzzzzz, password=ZZZZZZZZ, keepalive=0, ssl=True, ssl_params={}):
    And here’s “main.py”:
    def connect_mqtt(): global client_id, mqtt_server
    #client = MQTTClient(client_id, mqtt_server)
    client = MQTTClient(client_id, mqtt_server, user=zzzzzzzz, password=ZZZZZZZZ)

    Shell error dump:
    %Run -c $EDITOR_CONTENT
    Traceback (most recent call last):
    File “”, line 4, in
    File “umqttsimple.py”, line 11, in
    File “umqttsimple.py”, line 13, in MQTTClient
    NameError: name ‘zzzzzzzz’ isn’t defined
    Now I’m sorry, I had MQTT installed by version “Mosquitto Broker Enable Remote Access (No Authentication)”, everything worked.
    I uninstalled everything and reinstalled everything.

    I’m asking for help, which still needs to be changed. Thanks.

    Reply
    • Hi.
      You don’t need to change the umqttsimply.py file.
      You just need to modify the line in main.py that connects to the broker.
      client = MQTTClient(client_id, mqtt_server, user=zzzzzzzz, password=ZZZZZZZZ)
      Regards,
      Sara

      Reply
  21. There are en error en the guide.

    listener 1883 should be: listener 8883

    In the config file under:
    Mosquitto Broker Enable Remote Access (Authentication: user and password)

    Reply
    • Hi.
      Thanks for your comment.
      Port 8883 is for MQTT over TLS.
      We are not using TLS, so we use port 1883 (MQTT over TCP).
      Regards,
      SAra

      Reply
  22. Not sure what I did wrong, but the a/m procedure on a raspberry with rasbian resulted in
    mosquitto version 1.5.7 starting

    Reply
  23. I was getting an error when trying to use passwords, you missed a command

    mosquitto -c /etc/mosquitto/mosquitto.conf

    at least for me that fixed it

    Reply
  24. I am sorry to say that I am unable to get rid of the starting in local mode only.
    I have modified mosquitto.conf :
    per_listener_settings true is the first line without a #

    allow_anonymous false
    listener 1883
    password_file /etc/mosquitto/passwd

    are the last 3 lines.

    I have restarted the service yet on ‘mosquitto -v’ I still get starting in local mode only.
    I have shut down, unplugged, then restarted and till get local mode only
    I have tried ‘mosquitto -c /etc/mosquitto/mosquitto.conf’ and still now luck.

    Reply
  25. Are you sure it should work? Seems a little bit outdated:
    user@ACER-C22:~/Download$ sudo mosquitto_passwd -c /etc/mosquitto/passwd pavel
    sudo: mosquitto_passwd: command not found

    Reply
  26. Hi,
    Thanks for a great site.
    I have the same problem as David above.
    I am running version 2.011 on a Bullseye OS on a Raspberry Pi, which has been powering my smart home set up using node red.
    I have tried using the anonymous set up, and when that didnt work, i used the password set up, with the same results.

    Reply
  27. Hi Sara,

    thanks for the great article.
    I have followed all the steps to install mosquitto and clients on raspberry-PI.

    when tried with local-host for pub and sub on the raspberry-PI its working.
    But i try replacing with the Raspberry-PI’s IP address instead of local-host in below command it doesn’t work.

    can you please provide any valuable insights:

    pi@raspberrypi:~ $ mosquitto_pub -h 192.168.146.20 -t testing -m “hellofromPI” -p 1883 Error: Connection refused
    pi@raspberrypi:~ $

    please find below additional details:

    pi@raspberrypi:~ $ mosquitto -v 1661826620: mosquitto version 2.0.11 starting 1661826620: Using default config. 1661826620: Starting in local only mode. Connections will only be possible from clients running on this machine. 1661826620: Create a configuration file which defines a listener to allow remote access. 1661826620: For more details see https://mosquitto.org/documentation/authentication-methods/ 1661826620: Opening ipv4 listen socket on port 1883. 1661826620: Opening ipv6 listen socket on port 1883. 1661826620: mosquitto version 2.0.11 running

    pi@raspberrypi:~ $ mosquitto -version Error: Unknown option ‘-version’. mosquitto version 2.0.11 mosquitto is an MQTT v5.0/v3.1.1/v3.1 broker. Usage: mosquitto [-c config_file] [-d] [-h] [-p port] -c : specify the broker config file. -d : put the broker into the background after starting. -h : display this help. -p : start the broker listening on the specified port. Not recommended in conjunction with the -c option. -v : verbose mode – enable all logging types. This overrides any logging options given in the config file. See https://mosquitto.org/ for more information. pi@raspberrypi:~ $

    pi@raspberrypi:~ $ uname -a Linux raspberrypi 5.15.32-v7+ #1538 SMP Thu Mar 31 19:38:48 BST 2022 armv7l GNU/Linux pi@raspberrypi:~ $

    pi@raspberrypi:~ $ cat /etc/mosquitto/mosquitto.conf

    Place your local configuration in /etc/mosquitto/conf.d/

    #

    A full description of the configuration file is at

    /usr/share/doc/mosquitto/examples/mosquitto.conf.example

    pid_file /run/mosquitto/mosquitto.pid

    persistence true
    persistence_location /var/lib/mosquitto/

    log_dest file /var/log/mosquitto/mosquitto.log

    include_dir /etc/mosquitto/conf.d

    bind_interface eth0
    listener 1883 0.0.0.0
    allow_anonymous true

    Reply
    • Hi.
      How did you configure mosquitto?
      With username and password?
      Your mosquitto configuration file is different than the one in the tutorial.
      If you set user and password, you need to pass the user and password on your commands.
      Regards,
      Sara

      Reply
  28. How about an article on installing MQTT and/or Node-red on Orange pi? Nowadays it is increasingly difficult to find a raspberry pi even impossible, or at inflated prices. But there are alternatives like Orange pi or Banana pi that can be ordered from China at normal prices.

    Reply
  29. dear Sarah,

    I read your books with great interest and I am currently putting your SMART HOME book into practice.
    I’m blocked installing Mosquito on the Raspberry.
    I followed all the steps perfectly but when I try to connect with an ESP 8266, I get “Attempting MQTTconnection … failed, rc=-2 try again in 5 seconds”

    I read that others had the same problem. So there is something blocking.

    Could you help me?
    I put all the progress of what I did on the Raspberry several times without success.

    Thanks in advance

    (………………)

    Reply
  30. Buenas Sara.
    Lo primero, muy buen tutorial, cuesta encontrarlos!

    Todo me sale como en el tutorial, excepto cuando ejecuto:

    sudo systemctl restart mosquitto

    Que devuelve:
    “Job for mosquitto.service failed because the control process exited with error code.
    See “systemctl status mosquitto.service” and “journalctl -xe” for details”

    Al comprobar el estado del broker con:

    sudo systemctl status mosquitto
    o
    sudo systemctl status mosquitto.service

    Devuelve:
    feb 23 20:29:18 raspberrypi systemd[1]: mosquitto.service: Scheduled restart jo>
    feb 23 20:29:18 raspberrypi systemd[1]: Stopped Mosquitto MQTT Broker.
    feb 23 20:29:18 raspberrypi systemd[1]: mosquitto.service: Start request repeat>
    feb 23 20:29:18 raspberrypi systemd[1]: mosquitto.service: Failed with result ‘>
    feb 23 20:29:18 raspberrypi systemd[1]: Failed to start Mosquitto MQTT Broker.

    No se que puede estar pasando… Alguna idea?

    Gracias de antemano.

    Reply
  31. I have this problem:

    Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor preset: enabled)
    Active: failed (Result: exit-code) since Thu 2023-03-09 14:35:49 CET; 18min ago
    Docs: man:mosquitto.conf(5)
    man:mosquitto(8)
    Process: 653 ExecStartPre=/bin/mkdir -m 740 -p /var/log/mosquitto (code=exited, status=0/SUCCESS)
    Process: 654 ExecStartPre=/bin/chown mosquitto /var/log/mosquitto (code=exited, status=0/SUCCESS)
    Process: 655 ExecStartPre=/bin/mkdir -m 740 -p /run/mosquitto (code=exited, status=0/SUCCESS)
    Process: 656 ExecStartPre=/bin/chown mosquitto /run/mosquitto (code=exited, status=0/SUCCESS)
    Process: 657 ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf (code=exited, status=1/FAILURE)
    Main PID: 657 (code=exited, status=1/FAILURE)
    CPU: 56ms

    Mar 09 14:35:49 raspberrypi systemd[1]: mosquitto.service: Scheduled restart job, restart counter is at 5.
    Mar 09 14:35:49 raspberrypi systemd[1]: Stopped Mosquitto MQTT Broker.
    Mar 09 14:35:49 raspberrypi systemd[1]: mosquitto.service: Start request repeated too quickly.
    Mar 09 14:35:49 raspberrypi systemd[1]: mosquitto.service: Failed with result ‘exit-code’.
    Mar 09 14:35:49 raspberrypi systemd[1]: Failed to start Mosquitto MQTT Broker.

    Reply
  32. Hi Sara,
    This is a great project. I just finished configurinig the Mosquitto on my 64B RPI, and I followed everything to the dot. But, when I started the service I got the following error rmessage right a way. I can’t find anything in the log or the messages files::

    systemctl status mosquitto

    mosquitto.service – Mosquitto MQTT Broker
    Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor preset: enabled)
    Active: failed (Result: exit-code) since Wed 2023-03-22 12:47:30 EDT; 1min 7s ago
    .
    .
    Process: 655 ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf (code=exited, status=3)
    Main PID: 655 (code=exited, status=3)
    .
    .
    Mar 22 12:47:30 Rakhsh systemd[1]: mosquitto.service: Start request repeated too quickly.
    Mar 22 12:47:30 Rakhsh systemd[1]: mosquitto.service: Failed with result ‘exit-code’.
    Mar 22 12:47:30 Rakhsh systemd[1]: Failed to start Mosquitto MQTT Broker.

    Thank you so much.

    Givi

    Reply
  33. Ran into a problem, where the mosquitto broker runs on local IP (127.0.1.1), instead of it’s networked IP 192.168.2.135. I followed all steps of the tutorial installing mosquitto on a raspberry pi.

    hostname -i
    127.0.1.1

    Any idea how to get the broker to run on it’s networked IP?

    Reply
  34. Hi Sara,
    I am trying to use “User-name, Password” option for now. In mosquitto.conf file there is a commented option “acl_file”, so I uncommented it and added the path to the file name I am using.
    The first time I loaded it seem it corrupted the mosquitto.conf file and I was getting the annoying messages at boot up “Failed to start Mosquitto MQTT Broker.”. So, I had to use the saved original file again to get mosquitto load and start over again. However, I started mosquitto manually and “mosquitto Broker” loaded, But, I still see the annoying messages at boot up “Failed to start Mosquitto MQTT Broker.”. Is there a better way to use the ACL option? And how do I get rid of these annoying messages after a reboot etc.

    #acl_file
    acl_file /etc/mosquitto/myaclfile

    Thank you.

    Givi

    Reply
  35. Hi Sara,
    what a great project! It works properly.
    I would like to setup a MQTT project with one ESP32 as a subscriber and another ESP32 as publisher. The broker should be a RasPi standalone as Broker-Server creating its own WLAN without connection to the Internet via Router or Access Point.
    Can you give me hints how to do this?
    The handling of the ESP32 should be easy. But with the RasPi I have got my problems to combine the installed Mosquitto and the WLAN-Server capabilities.
    Do you have this setup described in one of your courses?
    Thanks!
    Oli

    Reply
  36. I am running version 11 of Raspian (bullseye)
    I am attempting to install mosquitto without authorization.
    All of the previous steps were completed successfully.
    When I get to step 4 (sudo systemctl restart mosquitto) I get the error message described by others. “Start request repeated too quickly”.

    Please help

    Reply
  37. Thank you for the tutorial.

    I’ve followed and tested the mosquitto according to your tutorials but I run into the following problem when trying to publish data from esp32 to the broker (yes, I’ve added user and password and clientId information to my esp32 code and modified the configuration file):

    Date time: New connection from on port 1883.
    Date time: New client connected from as (p5, c0, k60, u’username’).
    Date time: New connection from on port 1883.
    Date time: Client closed its connection.
    Date time: New connection from on port 1883.
    Date time: Client closed its connection.

    and so on.
    What might be the issue and how to fix it

    Reply
  38. Re: Authorisation and “To enable remote access so that we can communicate with other IoT devices”

    I am a bit of a novice, but I don’t understand the above. I have acquired some Zigbee devices and plan to use Zigbee2MQTT, for which a “broker” such as Mosquitto is required. So I will have “other IoT devices”, but I don’t think this Authorisation applies to access by them – I think it is access by humans TO them from a remote computer. Is that correct?

    Reply
  39. Hello, can you help me please with my issue. I was install mqtt client on Orange Pi Zero with Armbian. I just want to try by “mosquitto_sub -h localhost -t “testtopic” -v” and I receive “Connection error: Connection Refused: not authorised.” What can I do with that?
    Thank you!

    Reply
    • Hi.
      Did you set up username and password?
      Then, you need to add username and password to your commands.
      For example:

      mosquitto_sub -h localhost -t “testtopic” -v -u -P

      For example, in my case:

      mosquitto_sub -h localhost -t “testtopic” -v -u sara -P pass1245

      I hope this helps.
      Regards,
      Sara

      Reply
  40. I’m getting this order after restarting mosqitto:

    “Job for mosquitto.service failed because the control process exited with error code.
    See “systemctl status mosquitto.service” and “journalctl -xeu mosquitto.service” for details.”

    Reply
    • You need to look at the output from the commands above (e.g., the journalctl command). That should tell the problem it is probably that the mosquitto config file has an error in it. For example, it refers to a password file that doesn’t exist, there is a format error, etc.

      Reply
  41. Hi Sara,
    Followed the instructions for installing and running Mosquitto. Everything went as described until the restart of Mosquitto. I get this response: Any Ideas? I restarted the hardware a time or two, no difference. Using an RPI4. Selected no authentication.

    dan@RPI4-msata:~ $ sudo systemctl status mosquitto
    Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; preset: enabled)
    Active: failed (Result: exit-code) since Thu 2024-04-18 13:49:50 MDT; 1 day 4h ago
    Docs: man:mosquitto.conf(5)
    man:mosquitto(8)
    Process: 877 ExecStartPre=/bin/mkdir -m 740 -p /var/log/mosquitto (code=exited, status=0/SUCCESS)
    Process: 883 ExecStartPre=/bin/chown mosquitto /var/log/mosquitto (code=exited, status=0/SUCCESS)
    Process: 885 ExecStartPre=/bin/mkdir -m 740 -p /run/mosquitto (code=exited, status=0/SUCCESS)
    Process: 887 ExecStartPre=/bin/chown mosquitto /run/mosquitto (code=exited, status=0/SUCCESS)
    Process: 895 ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf (code=exited, status=1/FAILURE)
    Main PID: 895 (code=exited, status=1/FAILURE)
    CPU: 38ms

    Apr 18 13:49:50 RPI4-msata systemd[1]: mosquitto.service: Scheduled restart job, restart counter is at 5.
    Apr 18 13:49:50 RPI4-msata systemd[1]: Stopped mosquitto.service – Mosquitto MQTT Broker.
    Apr 18 13:49:50 RPI4-msata systemd[1]: mosquitto.service: Start request repeated too quickly.
    Apr 18 13:49:50 RPI4-msata systemd[1]: mosquitto.service: Failed with result ‘exit-code’.
    Apr 18 13:49:50 RPI4-msata systemd[1]: Failed to start mosquitto.service – Mosquitto MQTT Broker.

    Reply
    • Hi.
      Try to reboot your Raspberry Pi and then run that mosquitto command.
      Let me know if that solves the issue.
      Regards,.
      Sara

      Reply
      • Unfortunately, after performing the entire process all over again, the results are identical.
        As I said previously, re-booting doesn’t help. Thanks anyway.

        Reply
  42. Sara thank you for answering the questions for all these years.
    I have tried with both rpi3 Ang rpi5, installed broker and runs locally both mosquitto_sub and mosquitto_pub okay. I add listener 1883
    allow_anonymous true

    To mosquitto.conf file and save. Then I reboot RPi and check:
    Sudo systemctl status mosquitto

    Broker fails. I must be doing something wrong.
    Best regards.

    Reply
  43. Hello Sara,

    Thank a lot for this tutorial and the others.

    I have an issue when I try to enable the remote access.
    with “allow anonymous” mosquitto work fine and I can connect an other device
    If I follow your tutorial and try to set User/password, this doesn’t run and I get “error : address already in use ” on port 1883.
    If I change the port to 1884 in mosquitto.conf it’s run correctly.
    My question is: Why I can’t connect on 1883? (all mqtt devices have set on 1883).

    Thank for your help
    Jakl1

    Reply
    • Hi.
      The address already in use is not an error.
      You can still connect to the broker. Just make sure to use the username and password when trying to establish a connection.
      Regards,
      Sara

      Reply
  44. Hi Sara,
    Much thanks for this very clear tutorial. It worked out for me just fine.

    The link behind “Testing Mosquitto Broker and Client on Raspbbery Pi” on this page returns nothing. (An ever spinning wheel).

    Are you aware of that ? I’d thought I let you know.

    Rgds,
    Diederik from Netherlands.

    Reply
  45. Great tutorial. I have an account on a web host service with a fixed IP. I would really love to use it to host my MQTT broker but all my attempts and installing the required pieces have failed. Then I saw your tutorial. I wonder, is it possible to open the Raspberry Pi broker to the outside internet? I’m guessing I would need to use a Dynamic DNS to nail down the IP but I’m afraid I just don’t have all the pieces of this puzzle. Is it possible?

    Reply
    • Hi.
      We usually recommend using ngrok services to open a secure tunnel to your Raspberry Pi.
      Another good alternative is using Clouflare Tunnels.
      Regards,
      Sara

      Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.