Mosquitto is the most widely used MQTT broker, and a Raspberry Pi is the classic place to run it: small, cheap, always on, and close to your ESP32s, Node-RED and Home Assistant. A broker is the post office of MQTT: devices publish messages to named topics, and the broker delivers each message to every client subscribed to that topic, so sensors and dashboards never need to know about each other. (The full picture is in MQTT explained.) This guide installs it, tests it, opens it to your network securely, and connects your first devices. It works the same on a Pi 5, Pi 4, Pi 3 and Zero 2 W running Raspberry Pi OS.
Quick answer:
sudo apt update
sudo apt install -y mosquitto mosquitto-clients
sudo systemctl enable --now mosquittoSince Mosquitto 2.0, a fresh install only accepts connections from the Pi itself. To let ESP32s and other devices connect, add a config file with listener 1883, allow_anonymous false and a password_file, create a user with mosquitto_passwd, and restart. Then point your devices at the Pi's IP address on port 1883.
What You Need
- A Raspberry Pi (Zero 2 W, 3, 4 or 5) running Raspberry Pi OS and connected to your network
- A terminal on the Pi, or SSH from another computer
- The Pi's IP address, which
hostname -Ishows (step 6 covers it) - Optional: an ESP32, Node-RED or Home Assistant to connect once the broker is running
1. Install the Broker and Test Tools
Open a terminal on the Pi, or connect over SSH, and run:
sudo apt update
sudo apt install -y mosquitto mosquitto-clientsmosquitto is the broker; mosquitto-clients adds mosquitto_pub and mosquitto_sub, which let you test MQTT without any hardware. If a test fails with these tools, the problem is the broker, not your ESP32 code.
Check the version and that the service is running:
mosquitto -h | head -1 # e.g. mosquitto version 2.0.x
systemctl is-active mosquitto # active2. Start Mosquitto at Boot
sudo systemctl enable --now mosquitto
systemctl is-enabled mosquitto # enabledWhenever you change the configuration, restart and check it came back:
sudo systemctl restart mosquitto
systemctl is-active mosquitto
sudo journalctl -u mosquitto -n 30 --no-pager # the log, if it didn't startOn Raspberry Pi OS, messages marked retained and persistent sessions are saved to /var/lib/mosquitto/ (the default persistence true in /etc/mosquitto/mosquitto.conf), so they survive a reboot.
3. Test Publish and Subscribe on the Pi
Open two terminals. In the first, subscribe:
mosquitto_sub -h localhost -t 'test/hello' -vIn the second, publish:
mosquitto_pub -h localhost -t 'test/hello' -m 'hello from the Pi'The first terminal prints test/hello hello from the Pi. The broker works locally. Press Ctrl+C to stop the subscriber. More ways to test, including wildcards and retained messages, are in Test MQTT without hardware.
4. Why Other Devices Can't Connect Yet
Mosquitto 2.0 changed the default: with no listener line in the configuration, it listens only on localhost, so an ESP32 trying to reach 192.168.1.x:1883 gets connection refused. This is deliberate: older versions accepted anyone on the network with no password, and many brokers ended up open.
The fix is to add a listener and a login, in the next step.
Only for a quick test on a trusted network, you can accept anyone without a password by putting these two lines in /etc/mosquitto/conf.d/local.conf and restarting:
listener 1883
allow_anonymous trueAny device on your network can then read and publish every topic, including commands to your relays. Switch to the password setup below before you connect anything real. (The background is in the official Mosquitto 2.0 migration notes.)
5. Allow Network Access with a Username and Password
Create your own config file in conf.d (the main mosquitto.conf already includes everything in that folder):
sudo nano /etc/mosquitto/conf.d/local.confAdd these lines, save and exit:
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwdCreate the password file with your first user. -c creates the file:
sudo mosquitto_passwd -c /etc/mosquitto/passwd noderedAdd more users without -c. Running -c again silently replaces the file and deletes every existing user, the most common way people lock themselves out:
sudo mosquitto_passwd /etc/mosquitto/passwd esp32-garageGive the file to the broker's user and keep it private (recent versions warn about world-readable password files and will refuse them in future):
sudo chown mosquitto:mosquitto /etc/mosquitto/passwd
sudo chmod 0600 /etc/mosquitto/passwd
sudo systemctl restart mosquittoUse one account per device or service, so you can remove one without touching the others: delete a user with sudo mosquitto_passwd -D /etc/mosquitto/passwd esp32-garage and restart.
6. Test the Login, from the Pi and from Another Computer
Find the Pi's address first:
hostname -I # e.g. 192.168.1.20Subscribe with a username and password (use the Pi's IP now, not localhost):
mosquitto_sub -h 192.168.1.20 -t 'test/#' -u nodered -P 'your-password' -vPublish from another terminal or another computer:
mosquitto_pub -h 192.168.1.20 -t 'test/hello' -u nodered -P 'your-password' -m 'over the network'Then prove the lock works: publish without -u and -P. It should fail with Connection error: Connection Refused: not authorised.
On Windows or a Mac, the free MQTT Explorer app is the easiest way to watch every topic on the broker: enter the Pi's IP, port 1883 and a username. (Typing a password on the command line leaves it in your shell history; fine for a test account, not for real secrets.)
7. Limit What Each Device Can Do (ACLs)
A password decides who may connect; an access control list decides which topics each user may read or write. A garage sensor should publish its own readings, not switch your heating. Create the list:
sudo nano /etc/mosquitto/acl# Node-RED and Home Assistant: everything under home/
user nodered
topic readwrite home/#
# Testing only: remove this line when you are done
topic readwrite test/#
# Garage ESP32: publish its readings, receive only its own commands
user esp32-garage
topic write home/garage/#
topic read home/garage/cmd/#Point the broker at it by adding one line to /etc/mosquitto/conf.d/local.conf:
acl_file /etc/mosquitto/aclThen sudo chown mosquitto:mosquitto /etc/mosquitto/acl and restart. A publish to a topic a user isn't allowed is silently dropped, so if a device seems to send but nothing arrives, check the ACL first. That is also why the test/# line is there: without it, the step 6 test commands would silently stop working for nodered once the ACL is active. Topic layouts that make ACLs easy are covered in MQTT topic naming best practices.
8. Connect Your Devices
| Client | Broker setting |
|---|---|
| ESP32 / ESP8266 (PubSubClient) | client.setServer("192.168.1.20", 1883) and client.connect("esp32-garage", "esp32-garage", "password") |
| Node-RED | MQTT broker node: server localhost if it runs on the same Pi, port 1883, username and password in the Security tab |
| Home Assistant | Settings → Devices & Services → Add Integration → MQTT: broker IP, port 1883, username, password |
| MicroPython (umqtt) | MQTTClient("pico-1", "192.168.1.20", user="...", password="...") |
Give every device a unique client ID: two clients with the same ID keep disconnecting each other. Reserve the Pi's IP in your router so the address never changes, or use its hostname (raspberrypi.local) on clients that support mDNS.
Step-by-step client guides: ESP32 MQTT tutorial, Node-RED with Mosquitto, MQTT with ESP32 and Home Assistant, and MicroPython MQTT with umqtt.
Optional: WebSockets for browser dashboards
Web pages can't speak plain MQTT, but they can use MQTT over WebSockets. Add a second listener to local.conf:
listener 9001
protocol websocketsSince Mosquitto 2.0, each listener uses the same password and ACL settings unless you set per_listener_settings true, so the WebSocket port is protected too.
If a firewall is enabled
Raspberry Pi OS has no firewall by default. If you've enabled ufw, allow the ports from your local network only:
sudo ufw allow from 192.168.1.0/24 to any port 1883 proto tcpNo Raspberry Pi? Run Mosquitto on a Windows PC
You don't need a Pi to follow this guide. Mosquitto has a Windows installer, and an ESP32 or ESP8266 on the same Wi-Fi can publish to it exactly as it would to a Pi. The broker is the same software, so the passwords, topics and ACLs above work unchanged. Only the install and the file paths differ. A PC has to stay switched on for the broker to be reachable, which is why a Pi is the better long-term home.
1. Install. Download the Windows installer from mosquitto.org/download and run it with the defaults (leave install as a service ticked). Open PowerShell as Administrator (right-click PowerShell, Run as administrator) and check:
Get-Service mosquittoIt should say Running. Out of the box the broker only accepts connections from the PC itself, with no password.
2. Create a user. The files live in C:\Program Files\mosquitto. The first command creates the password file (-c creates it and wipes any existing users, so use it once); -b takes the password from the command line, which is fine for a test account:
cd "C:\Program Files\mosquitto"
.\mosquitto_passwd.exe -c -b passwd esp32-garage Garage12345To change a password later, run the same command without -c.
3. Allow other devices. Open mosquitto.conf in Notepad (notepad mosquitto.conf), add these three lines at the very bottom, and save:
listener 1883
allow_anonymous false
password_file C:\Program Files\mosquitto\passwd4. Restart the broker and open the firewall. The broker only reads its config at start-up, so editing the file isn't enough:
net stop mosquitto
net start mosquitto
New-NetFirewallRule -DisplayName "Mosquitto MQTT" -Direction Inbound -Protocol TCP -LocalPort 1883 -Action AllowConfirm it now listens on the network, not just on the PC:
netstat -ano | findstr :1883You want 0.0.0.0:1883 ... LISTENING. If you only see 127.0.0.1:1883, the broker is still running with its old settings.
5. Find the PC's address. Run ipconfig and read IPv4 Address under Wireless LAN adapter WiFi (for example 192.168.1.39). Ignore the Hyper-V and WSL adapters. This is the address your ESP32 or ESP8266 uses as its broker. (Give the PC a fixed address in your router, or the address may change and the device will stop connecting.)
6. Point the device at it. The sketch needs the PC's address, port 1883, and the username and password. In PubSubClient the order is connect(clientId, username, password):
const char* MQTT_HOST = "192.168.1.39";
mqtt.connect("garage-esp8266-1", "esp32-garage", "Garage12345");Complete sketches: ESP32 MQTT publish and subscribe and NodeMCU ESP8266 MQTT LED control.
7. Watch it in MQTT Explorer. Add a new connection with host localhost, port 1883, protocol mqtt://, and your username and password. When the device is publishing you'll see its topics appear (the MQTT Explorer screenshot after the ACL section shows home/garage).
If the Windows service keeps stopping
If Get-Service mosquitto shows Stopped again right after net start, you can run the broker in a window instead. It prints every connection and the reason a login is refused, which makes it the best way to debug:
cd "C:\Program Files\mosquitto"
.\mosquitto.exe -c mosquitto.conf -vLeave the window open while you test, and don't run net start at the same time (both would want port 1883). A healthy connection looks like New connection from 192.168.1.41 followed by Client ... connected.
Windows troubleshooting: what each error means
| What you see | Meaning | Fix |
|---|---|---|
MQTT Explorer: getaddrinfo ENOTFOUND mqtt.eclipse.org | A saved connection to a public broker that no longer exists is selected | Create a new connection with host localhost instead of editing the old one |
Works on localhost, but the ESP gets rc=-2 | Broker listening only on 127.0.0.1 (config not loaded yet), or the firewall blocks port 1883 | Restart the broker; check netstat shows 0.0.0.0:1883; create the firewall rule |
rc=-2 even though the PC looks fine | Wrong broker address in the sketch, or the device joined a different Wi-Fi network | The IP: line in the Serial Monitor must be in the same range as the PC (for example 192.168.1.x); re-check MQTT_HOST |
Broker window: disconnected: not authorised (ESP prints rc=5) | Username or password in the sketch doesn't match | Reset it with mosquitto_passwd.exe -b passwd user newpass (no -c) and make the sketch match exactly, including capitals and spaces |
ESP prints rc=2 | The broker rejected the client ID | Use a short, plain, non-empty ID as the first argument of connect(), and keep the order (clientId, username, password) |
net start mosquitto succeeds but the service shows Stopped | The service exits on start | Run it in a window with -c mosquitto.conf -v as above, and read the messages |
Everything worked yesterday, now rc=-2 | The PC's IP address changed (DHCP) | Run ipconfig, update MQTT_HOST, or reserve the address in your router |
To prove the login works without any hardware, subscribe from the PC itself (this connects, then waits for a message; press Ctrl+C to stop):
.\mosquitto_sub.exe -h localhost -u esp32-garage -P Garage12345 -t "#" -vIf that connects, the broker and the user are fine, and any remaining problem is in the device's sketch or its network. Return codes in general: MQTT troubleshooting: connection refused, rc=-2 and rc=5.
Don't expose this PC's port 1883 to the internet. Passwords alone aren't enough over plain MQTT; keep the broker on your home network, and read the security checklist below before going further.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Works on the Pi, Connection refused from other devices | No listener 1883 line (Mosquitto 2.0 default) | Add the listener as in step 5 and restart |
not authorised / PubSubClient rc=5 | Wrong username or password, or no user for that name | Re-add the user with mosquitto_passwd (no -c); check the spelling |
| Every user stopped working | mosquitto_passwd -c was run again and recreated the file | Recreate each user without -c |
PubSubClient rc=-2 | Can't reach the broker at all | Wrong IP, Pi offline, firewall, or ESP32 not on Wi-Fi |
| Service won't start after an edit | Syntax error, or a file the broker can't read | sudo journalctl -u mosquitto -n 30; check paths and chown mosquitto |
| Duplicate listener error on start | The same port defined twice (e.g. in mosquitto.conf and conf.d) | Keep each listener line in one file |
| Messages sent but never received | ACL blocks the topic, or topic spelling or case differs | Check the ACL; topics are case-sensitive |
| Clients keep disconnecting each other | Two clients share a client ID | Make every client ID unique |
Return codes and more causes are explained in MQTT troubleshooting: connection refused, rc=-2 and rc=5.
Security Checklist
allow_anonymous falseand a password for every client.- One account per device, and an ACL so each can only use its own topics.
- Never port-forward 1883 to the internet. To reach the broker from outside, use a VPN such as Tailscale or WireGuard, or a cloud broker with TLS on port 8883.
- Keep the Pi updated:
sudo apt update && sudo apt upgrade. - Test that a wrong password fails, not just that the right one works.
- Back up
/etc/mosquitto/along with the rest of your configuration.
FAQ
Does Mosquitto run on a Raspberry Pi Zero 2 W or Pi 4? Yes, with the same commands. It needs very little CPU or memory; a Zero 2 W easily handles a home's worth of sensors.
What's the default Mosquitto port? 1883 for plain MQTT, 8883 for MQTT over TLS, and commonly 9001 for WebSockets.
Where is the config file? /etc/mosquitto/mosquitto.conf, which includes every .conf file in /etc/mosquitto/conf.d/. Put your own settings in conf.d.
How do I see what's happening on the broker? mosquitto_sub -h localhost -t '#' -v -u nodered -P '...' prints every message on every topic.
Can Mosquitto and Node-RED run on the same Pi? Yes, and that's the usual setup; Node-RED then connects to localhost. See install Node-RED on the Raspberry Pi 5.
How do I check that Mosquitto is running? systemctl is-active mosquitto prints active. systemctl status mosquitto adds detail and the last few log lines.
Where are the Mosquitto logs? sudo journalctl -u mosquitto -f follows the live log. On Raspberry Pi OS the default configuration also writes to /var/log/mosquitto/mosquitto.log.
How do I change a user's password? Run sudo mosquitto_passwd /etc/mosquitto/passwd username without -c, type the new password twice, then sudo systemctl restart mosquitto.
Why does Mosquitto work on the Pi but say "Connection refused" from my ESP32? Mosquitto 2.0 only listens on localhost until you add a listener line. See step 4 above, then add the listener and password file from step 5.
How do I uninstall Mosquitto? sudo apt remove --purge mosquitto mosquitto-clients, then sudo apt autoremove. Purging deletes /etc/mosquitto/, so back up your password and ACL files first.
Official references: mosquitto.conf manual · authentication methods
Next Steps
- Test MQTT without hardware using only the command-line tools
- MQTT explained: broker, topics, QoS, retained messages and LWT
- ESP32 MQTT publish and subscribe
- Node-RED with Mosquitto to build a dashboard on the same Pi



