Setup and Secure MQTT websocket broker with Nginx
MQTT stands for Message Queuing Telemetry Transport. MQTT is a lightweight, publish-subscribe network protocol that transports messages between devices. An MQTT broker is a server that receives all messages from the clients and then routes the messages to the appropriate destination clients.
Overview
- Download Mosquitto MQTT.
- Build and Install Mosquitto MQTT with websocket enabled.
- Configure Mosquitto MQTT.
- Install Nginx and configure.
- Install Certbot and create certificate.
- Test Everything.
Links
- Mosquitto MQTT (Version: 2.0.10):
- Online Test Tool: http://tools.emqx.io/ (Do not use your original credentials it may get compromised.)
Steps
- First update the os.
sudo apt update && sudo apt upgrade -y
Install some packages.
sudo apt install -y libwebsockets-dev build-essential libcjson1 libcjson-dev
Download Mosquitto MQTT broker.
wget https://mosquitto.org/files/source/mosquitto-2.0.10.tar.gz
2. Build and Install Mosquitto MQTT with websocket enabled.
tar -xvf mosquitto-2.0.10.tar.gz
cd mosquitto-2.0.10/
make WITH_WEBSOCKETS=yes
sudo make install
mosquitto --version
3. Configure Mosquitto MQTT.
sudo mkdir /var/lib/mosquitto /etc/mosquitto/conf.d /var/log/mosquitto/
sudo touch /var/run/mosquitto.pid
create mosquitto.conf
and write below configuration.
sudo vi /etc/mosquitto/mosquitto.conf
save and exit the file.
now let’s create user for broker.
sudo mosquitto_passwd -c /etc/mosquitto/passwd admin_user
Now let’s start the MQTT broker.
sudo systemctl daemon-reload
sudo systemctl start mosquitto.service
sudo systemctl status mosquitto.service
Note: You can check logs at /var/log/mosquitto/mosquitto.log
4. Now, It’s time to install and configure Nginx.
sudo apt -y install nginx nginx-common
create rule for MQTT broker.
sudo vi /etc/nginx/conf.d/mqtt.conf
save and exit the file.
sudo ngixn -t
sudo systemctl restart nginx.service
sudo systemctl status nginx.service
5. Install Certbot and create certificate.
sudo apt install -y certbot python3-certbot-nginxsudo certbot --nginx -d mqtt.sujitpatel.in#Follow certbot instructions to continue.sudo systemctl restart nginx.service
6. Now, it’s time to test everything.
Go to http://tools.emqx.io/
click on + icon.
enter connection details.
use wss
protocol and port 443
.
(Do not use your production credentials)