Install MQTT Server - ajumalp/rpi-nas GitHub Wiki

Install Broker

To Install MQTT Broker using below command

sudo apt install -y mosquitto mosquitto-clients

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

Enable Remote Access/ Authentication

No Authentication

Run the following command to open the mosquitto.conf file

sudo nano /etc/mosquitto/mosquitto.conf

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

listener 1883
allow_anonymous true

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

sudo systemctl restart mosquitto

Authentication: user and password

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

sudo mosquitto_passwd -c /etc/mosquitto/passwd YOUR_USERNAME

Run the following command to edit the configuration file

sudo nano /etc/mosquitto/mosquitto.conf

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

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

# 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

image
Press CTRL-X, then Y, and finally press Enter to exit and save the changes Restart Mosquitto for the changes to take effect

sudo systemctl restart mosquitto