Setup and Secure MQTT websocket broker with Nginx

Sujit Patel
2 min readApr 10, 2022

--

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.

Architecture of MQTT

Overview

  1. Download Mosquitto MQTT.
  2. Build and Install Mosquitto MQTT with websocket enabled.
  3. Configure Mosquitto MQTT.
  4. Install Nginx and configure.
  5. Install Certbot and create certificate.
  6. Test Everything.

Links

  1. Mosquitto MQTT (Version: 2.0.10):
  2. Online Test Tool: http://tools.emqx.io/ (Do not use your original credentials it may get compromised.)

Steps

  1. 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)

--

--

Sujit Patel
Sujit Patel

Written by Sujit Patel

DevOps Engineer, Linux lover, Technology and Automation enthusiast. A strong believer in continuous learning.

No responses yet