Run Your Cloud MQTT Mosquitto Broker (access from anywhere using Digital Ocean)

This guide explains how to install Mosquitto Broker for MQTT communication on a Linux Ubuntu VM (Virtual Machine) using Digital Ocean. Running an 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. You’ll also learn how to connect your ESP boards to the cloud MQTT broker using Arduino IDE.

Run Your Cloud MQTT Mosquitto Broker access from anywhere in the world using Digital Ocean

Introducing MQTT Protocol

We have a guide that introduces you to the MQTT protocol. MQTT stands for Message Queuing Telemetry Transport. It is a lightweight publish and subscribe system where you can publish and receive messages as a client. Read What is MQTT and how it works.

An MQTT broker is primarily responsible for receiving all MQTT messages, filtering the messages, decide who is interested in each message and then, publishing the messages to all subscribed clients.

Mosquitto MQTT Broker publish subscribe example messages

There are several brokers you can use. In our Home Automation projects and tutorials we use the popular Mosquitto MQTT Broker. It is easy to install, configure and use.

In this tutorial, it will be installed on a Linux Ubuntu VM (virtual machine) running on Digital Ocean hosting service.

Cloud MQTT Broker Overview

What’s the advantage of using a Cloud MQTT broker and how it works?

Using a Cloud MQTT broker allows you to have several IoT devices (like ESP32 and ESP8266 boards) communicating with each other using MQTT, even if they are on different networks (different locations connected to different routers). Here’s an overview.

ESP32 ESP8266 Digital Ocean MQTT Mosquitto Broker Overview
  • Mosquitto MQTT broker is running on the cloud (host service provided by Digital Ocean). So, it can receive messages from IoT devices all around the world.
  • You can have several ESP boards on different networks that use that Cloud MQTT broker.
  • Each ESP board needs to be connected to a router that allows access to the internet in order to connect with the broker.
  • Because the boards use the same MQTT broker, they can communicate with each other by publishing and subscribing to the same topics.

The following diagram shows an example of a possible application:

ESP32 ESP8266 Digital Ocean MQTT Mosquitto Broker Overview Publish Subscribe
  • The previous image shows two ESP32 boards on different networks. Each board is connected to a different router with access to the internet.
  • Even though they are on different networks, they can communicate with each other using the Cloud MQTT broker by subscribing and publishing on the same topics.
  • ESP32 #1 publishes on a topic that ESP32 #2 is subscribed to (board2/output1). The message can indicate whether ESP32 #2 should turn an output on or off. So, ESP32 #1 can control the ESP32 #2 outputs.
  • Similarly, ESP32 #2 publishes temperature readings on the board2/temperature topic. ESP32 #1 is subscribed to that topic, so it receives board2 sensor readings.

You can also install Node-RED on the same cloud (Digital Ocean hosting account) to control and monitor your boards from anywhere in the world using your computer or your smartphone. You can follow this tutorial: Access Node-RED Dashboard from Anywhere using Digital Ocean

Hosting Service – Digital Ocean

To run your Cloud MQTT Mosquitto Broker, you need to use a hosting service that allows you to have access to the command line and install any software that you need. I recommend using Digital Ocean that offers an Ubuntu server that you can manage through a command line.

I’ve been using it since 2015 and I personally recommend it, but you can use any other hosting service. Any hosting service that offers a Linux Ubuntu VM with full console access should work.

If you don’t have a hosting account, I recommend signing up for Digital Ocean. When you sign up for Digital Ocean, you can try it for 60 days (they give you free credits to test the platform).

Grab Linux Ubuntu VM on Digital Ocean »

If you like our projects, you might consider signing up to the recommended hosting service, because you’ll be supporting our work.

Note: you can also run Mosquitto MQTT Broker in your local network using a Raspberry Pi board. However, the purpose of this tutorial is to run an MQTT broker in the cloud to communicate with boards (or other IoT devices) across different networks.

Creating Digital Ocean Account

To create a Digital Ocean Account, go to Digital Ocean and press the “Sign Up” button.

Digital Ocean VPN Mosquitto MQTT Broker Installation

Create your account, and you’ll receive a $100 credit that you can use for 60 days to test the platform. You might need to enter a valid credit card, but you can cancel your account anytime if you’re no longer interested in using the service after the free 60 days trial.

Complete the account creation using your preferred method (I always use the Email option).

Digital Ocean VPN Sign Up Mosquitto MQTT Broker Installation

Confirm your account and login, you should see a similar Dashboard.

Digital Ocean Login Dashboard Mosquitto MQTT Broker

Create a Droplet (Linux Ubuntu VM)

To create a new VM, press the “Create” button on the top right corner and select the “Droplets” option. Digital Ocean calls Droplets to its VMs.

Important: if you’re already running a Droplet with Node-RED installed, you can skip these next steps (creating a Droplet). You can run both Node-RED and Mosquitto MQTT broker in the same server.

Digital Ocean VPN Create Droplet Mosquitto MQTT Broker

For this guide I’ll be using Ubuntu 20.04 (LTS) x64, and I recommend choosing the same option. You can also use the “Basic” starter plan.

Digital Ocean VPN Droplet Linux Ubuntu Mosquitto MQTT Broker

In the VM resources menu, you can choose the cheapest plan for $5/month. Even with the lowest plan, it will run the MQTT Broker and Node-RED smoothly .

Digital Ocean VPN Sign Up Droplet Pricing Mosquitto MQTT Broker

Choose the Virtual Machine datacenter location closer to you, in my case I’ve used “London” region.

Digital Ocean VPN Linux Ubuntu Server Location Mosquitto MQTT Broker Installation

Create the root password that allows you to access your Droplet (save this password, because you’ll need it to access your server).

Digital Ocean VPN Linux Ubuntu Server Set Define Password

Finally, choose a hostname to easily identify which Virtual Machine you are working with. I’ve named my Droplet as “mqtt-cloud-server”. That’s it, you just need to press the big green button “Create Droplet” to finish the process.

Digital Ocean VPN Linux Ubuntu Server Set Define Hostname Create Droplet

Wait a few minutes and when the progress bar ends, your Droplet is ready.

Accessing Your Linux Ubuntu VM Console

When your Droplet is prepared, open your newly created server (in my case, it’s called “mqtt-cloud-server“).

Digital Ocean VPN Linux Ubuntu Server Open Droplet

Select the “Access” menu and press the “Launch Console” button.

Digital Ocean VPN Linux Ubuntu Server Open Launch Console

A new browser window opens up in your computer.

Digital Ocean VPN Linux Ubuntu Server Login Console

Type your login (root) and the password defined earlier, press Enter key to access your server.

Digital Ocean VPN Linux Ubuntu Server Login Console Username Password

There’s an optional step, but it goes beyond the scope of this tutorial. It’s not required to make this project work: prepare your server with non-root, sudo-enabled user and basic firewall with this Initial Server Setup with Ubuntu 20.04.

Installing Mosquitto MQTT Broker on Linux Ubuntu VM Digital Ocean

Let’s install the Mosquitto Broker.

Mosquitto MQTT Broker Logo

Before installing the software, update and upgrade your server (this will take a few minutes to complete).

sudo apt update && sudo apt upgrade -y

To install MQTT Mosquitto Broker on Ubuntu, run:

sudo apt install mosquitto mosquitto-clients -y

That’s it! Mosquitto MQTT broker is installed.

Testing MQTT Mosquitto Broker Installation

To test your MQTT broker installation, you can use another terminal window (Terminal window #2) and establish an SSH communication with your server (you can use PuTTY or a similar SSH client).

SSH Client Connecting To Digital Ocean Server Putty

Login as root and enter your password.

Then, enter the following command to subscribe to the test topic.

mosquitto_sub -h localhost -t test

In your Terminal window #1, use the next command to publish the message “Hello, world!” in the test topic:

mosquitto_pub -h localhost -t test -m "Hello, world!"
Testing Mosquitto MQTT Broker on Linux Ubuntu

Terminal window #2 should receive the message as illustrated below:

Installing Mosquitto MQTT Broker on Linux Ubuntu

Securing Your MQTT Broker (Authentication with Username and Password)

At the moment, anyone that knows your MQTT Broker IP address can publish and subscribe to your MQTT topics. We can secure the MQTT Broker installation by adding a required authentication with username and password.

Enter a similar 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 as ruisantos. :

sudo mosquitto_passwd -c /etc/mosquitto/passwd ruisantos

When you run the preceding command with the desired username, you’ll be asked to enter a password. Enter the a password and save the user/pass combination. You’ll need it to authenticate the broker later in this guide.

Finally, open the default.conf to edit it by running the following command:

sudo nano /etc/mosquitto/conf.d/default.conf

Add these two lines to require authenticated users to publish MQTT message and subscribe to MQTT topics.

allow_anonymous false
password_file /etc/mosquitto/passwd

Your file should look like this:

Installing Mosquitto MQTT Broker on Linux Ubuntu

Exit the file and save it (Ctrl+X, Y, Enter key) and restart your MQTT broker for the changes to take effect:

sudo systemctl restart mosquitto

Now, if you try to publish a new message without providing the user/pass:

mosquitto_pub -h localhost -t test -m "Hello, world!"

You’ll get the “Connection error: Connection Refused: not authorised.”

Installing Mosquitto MQTT Broker on Linux Ubuntu

Now, subscribe to the MQTT test topic using the -u an -P arguments to make the authentication as follows:

mosquitto_sub -h localhost -t test -u "ruisantos" -P "YOUR_PASSWORD"
Testing Mosquitto MQTT Broker on Linux Ubuntu Subscribe to MQTT Topic

And do the same thing to publish a message:

mosquitto_pub -h localhost -t test -m "Hello, world!" -u "ruisantos" -P "YOUR_PASSWORD"
Testing Mosquitto MQTT Broker on Linux Ubuntu Publish MQTT Message to Topic

Use the next table as a reference for the parameters you can pass in mosquitto_sub and mosquitto_pub commands:

-hHostname
-tMQTT topic
-mMQTT message
-uMQTT username
-PMQTT Password

Connecting Your ESP32 to MQTT Mosquitto Broker

For us at the RNT Blog, we often use MQTT brokers in our ESP32 and ESP8266 projects, so let’s test how you can connect the ESP32 board to your Cloud MQTT Broker.

Before proceeding with this tutorial, make sure you complete the following prerequisites.

Arduino IDE

We’ll program the ESP32 board using Arduino IDE, so make sure you have the ESP32 add-on installed.

MQTT Libraries

To use MQTT with the ESP32 we’ll use the Async MQTT Client Library.

Installing the Async MQTT Client Library

  1. Click here to download the Async MQTT client library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get async-mqtt-client-master folder
  3. Rename your folder from async-mqtt-client-master to async_mqtt_client
  4. Move the async_mqtt_client folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch Include Library > Add . ZIP library and select the library you’ve just downloaded.

Installing the Async TCP Library

To use MQTT with the ESP, you also need the Async TCP library.

  1. Click here to download the Async TCP client library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get AsyncTCP-master folder
  3. Rename your folder from AsyncTCP-master to AsyncTCP
  4. Move the AsyncTCP folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch Include Library > Add . ZIP library and select the library you’ve just downloaded.

ESP32 MQTT Publish Messages to Cloud MQTT Broker

Copy the following code to your Arduino IDE. To make it work for you, you need to insert your network credentials as well as the MQTT broker details (your Digital Ocean Droplet’s IP Address, broker username and password).

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/cloud-mqtt-mosquitto-broker-access-anywhere-digital-ocean/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMqttClient.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Digital Ocean MQTT Mosquitto Broker
#define MQTT_HOST IPAddress(XXX, XXX, XXX, XXX)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#define MQTT_PORT 1883

#define MQTT_USERNAME "REPLACE_WITH_YOUR_MQTT_USER"
#define MQTT_PASSWORD "REPLACE_WITH_YOUR_MQTT_PASSWORD"

// Test MQTT Topic
#define MQTT_PUB_TEST "test"

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 5000;         // Interval at which to publish sensor readings

int i = 0;

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
  }
}

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}*/

void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void setup() {
  Serial.begin(115200);
  Serial.println();

  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  /*mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);*/
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  mqttClient.setCredentials(MQTT_USERNAME, MQTT_PASSWORD);
  connectToWifi();
}

void loop() {
  unsigned long currentMillis = millis();
  // Every X number of seconds (interval = 5 seconds) 
  // it publishes a new MQTT message
  if (currentMillis - previousMillis >= interval) {
    // Save the last time a new reading was published
    previousMillis = currentMillis;
    
    String testString = "Hello, world! #" + String(i);
    // Publish an MQTT message on topic test
    uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEST, 1, true, String(testString).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEST, packetIdPub1);
    Serial.printf(" Message: %.2f \n", testString);
    i++;
  }
}

View raw code

Type your network credentials on the following lines.

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Insert the Digital Ocean Droplet IP address, so that the ESP32 connects to your broker (in my case, it is 178.62.83.231).

#define MQTT_HOST IPAddress(178, 62, 83, 231)

If your broker requires authentication, type your MQTT username and MQTT password.

#define MQTT_USERNAME "YOUR_USER"
#define MQTT_PASSWORD "YOUR_PASSWORD"

Testing ESP32 MQTT Publishing Messages

If you have your ESP32 running the uploaded code and you open your Arduino IDE Serial monitor, you’ll see that your ESP32 is publishing new messages every 5 seconds.

ESP32 ESP8266 Publish MQTT Message to Cloud Mosquitto MQTT Broker

Establish an SSH connection with your SSH client (like PuTTY) and type:

mosquitto_sub -h localhost -t test -u "YOUR_USER" -P "YOUR_PASSWORD"

You should start receiving new MQTT messages published by your ESP32.

ESP32 ESP8266 Subscribe to MQTT topic receive Message Cloud Mosquitto MQTT Broker

Cloud MQTT Broker Publish Messages to ESP32

The next sketch makes the ESP32 subscribe to a cloud MQTT topic to receive messages. Copy it to your Arduino IDE, then insert your network credentials as well as the MQTT broker details (your Digital Ocean Droplet’s IP Address and the broker username and password).

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/cloud-mqtt-mosquitto-broker-access-anywhere-digital-ocean/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMqttClient.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Digital Ocean MQTT Mosquitto Broker
#define MQTT_HOST IPAddress(XXX, XXX, XXX, XXX)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#define MQTT_PORT 1883

#define MQTT_USERNAME "REPLACE_WITH_YOUR_MQTT_USER"
#define MQTT_PASSWORD "REPLACE_WITH_YOUR_MQTT_PASSWORD"

// Test MQTT Topic
#define MQTT_SUB_TEST "test"

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 5000;         // Interval at which to publish sensor readings

int i = 0;

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
  }
}

// Add more topics that want your ESP to be subscribed to
void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
  
  // ESP subscribed to test topic
  uint16_t packetIdSub = mqttClient.subscribe(MQTT_SUB_TEST, 0);
  Serial.println("Subscribing at QoS 0");
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}

void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

// You can modify this function to handle what happens when you receive a certain message in a specific topic
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  String messageTemp;
  for (int i = 0; i < len; i++) {
    //Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  // Check if the MQTT message was received on topic test
  if (strcmp(topic, MQTT_SUB_TEST) == 0) {
    Serial.println("TRUE");
  }
 
  Serial.println("Publish received.");
  Serial.print("  message: ");
  Serial.println(messageTemp);
  Serial.print("  topic: ");
  Serial.println(topic);
  Serial.print("  qos: ");
  Serial.println(properties.qos);
  Serial.print("  dup: ");
  Serial.println(properties.dup);
  Serial.print("  retain: ");
  Serial.println(properties.retain);
  Serial.print("  len: ");
  Serial.println(len);
  Serial.print("  index: ");
  Serial.println(index);
  Serial.print("  total: ");
  Serial.println(total);
}

/*void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}*/

void setup() {
  Serial.begin(115200);
  Serial.println();

  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  //mqttClient.onPublish(onMqttPublish);
  mqttClient.onMessage(onMqttMessage);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  mqttClient.setCredentials(MQTT_USERNAME, MQTT_PASSWORD);
  connectToWifi();
}

void loop() {
  
}

View raw code

Type your network credentials on the following lines.

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Insert the Digital Ocean Droplet IP address, so that the ESP32 connects to your broker (in my case, it is 178.62.83.231).

#define MQTT_HOST IPAddress(178, 62, 83, 231)

If your broker requires authentication, type your MQTT username and MQTT password.

#define MQTT_USERNAME "YOUR_USER"
#define MQTT_PASSWORD "YOUR_PASSWORD"

Testing ESP32 Subscribe to MQTT Topic

To test if your ESP32 is receiving MQTT messages, in your Digital Ocean console start publishing different messages (for example “Hi #1!“, “Hi #2!“, etc).

mosquitto_pub -h localhost -t test -m "Hi #1!" -u "ruisantos" -P "YOUR_PASSWORD"
mosquitto_pub -h localhost -t test -m "Hi #2!" -u "ruisantos" -P "YOUR_PASSWORD"
mosquitto_pub -h localhost -t test -m "Hi #3!" -u "ruisantos" -P "YOUR_PASSWORD"
Cloud Mosquitto MQTT Broker Publish MQTT Message Topic to ESP32 ESP8266 NodeMCU

Your ESP32 should receive each message and print it in the Serial Monitor, as shown in the image below.

ESP32 ESP8266 NodeMCU Subscribed to MQTT topic Receive MQTT message Cloud MQTT broker

In these quick examples, we’ve shown you how to publish and subscribe MQTT messages using the Cloud MQTT broker. The idea is to use several ESP32 or ESP8266 boards that publish and subscribe to the same topics to communicate with each other and/or use Node-RED on the cloud to interact with those boards.

(Optional) Taking It Further – MQTT Mosquitto Broker Encrypted Requests

The best method to add an SSL certificate to your server is by having a domain name pointed at your server and using Let’s Encrypt certificates.

Having a domain name and Let’s Encrypt SSL Certificates ready, follow the next instructions to secure your Mosquitto broker.

To enable SSL encryption, we need to tell Mosquitto where our Let’s Encrypt certificates are stored. Open up the configuration file we previously started:

sudo nano /etc/mosquitto/conf.d/default.conf

Add the next lines to make your default.conf add the Let’s Encrypt certificates.

allow_anonymous false
password_file /etc/mosquitto/passwd

listener 1883 localhost

listener 8883
certfile /etc/letsencrypt/live/example.com/cert.pem
cafile /etc/letsencrypt/live/example.com/chain.pem
keyfile /etc/letsencrypt/live/example.com/privkey.pem

Listener 1883 is the standard unencrypted MQTT port. The localhost instructs Mosquitto to only bind this port to the localhost interface, so it’s not longer accessible externally.

On the other hand, listener 8883 sets up an encrypted listener on port 8883. The next three lines point Mosquitto to the appropriate Let’s Encrypt files to set up the encrypted connections.

Save and exit the file (Ctrl+X, Y, Enter key), then restart Mosquitto to update the settings:

sudo systemctl restart mosquitto

Update the firewall to allow connections to port 8883.

sudo ufw allow 8883

Now, you subscribe to the test MQTT topic in the encrypted port (8883). Don’t forge to replace example.com with your domain name in the subscribe and publish commands.

mosquitto_sub -h example.com -t test -p 8883 --capath /etc/ssl/certs/ -u "ruisantos" -P "YOUR_PASSWORD"

You can publish encrypted messages:

mosquitto_pub -h example.com -t test -m "Secure message" -p 8883 --capath /etc/ssl/certs/ -u "ruisantos" -P "YOUR_PASSWORD"

With this setup, you’ll need to prepare your ESP32/ESP8266 to make encrypted MQTT requests on port 8883.

Wrapping Up

This complete guide was tested and it should work, however there are many steps and they must be followed exactly as we describe, otherwise something might not work properly.

In all our guides and projects we always try to help if anyone gets stuck. However, in this particular case, there are so many steps that it can be extremely hard to help you without having access to the server and test it (of course, we don’t have the resources to personally help everyone).

If you have any problem installing Mosquitto MQTT broker, preparing your Linux Ubuntu server, running Node-RED, installing an SSL certificate, contact Digital Ocean support and describe exactly what’s happening. I’ve been using their service since 2015 and they always have an extremely helpful support team (or just use their Forum).

Now, if you want to install Node-RED on Digital Ocean, follow the next tutorial: Access Node-RED Dashboard from Anywhere using Digital Ocean.

Read the next guides to learn more about MQTT:

Thanks for reading.



Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

10 thoughts on “Run Your Cloud MQTT Mosquitto Broker (access from anywhere using Digital Ocean)”

  1. Rui you are a real clever man! How do you do all these?
    Any way I struggled to make Cloud MQTT Mosquitto Broker at DigitalOcean during these Covid-19 scare period. I also succeeded in capturing my messages into a mysql database.
    I borrowed heavily on your ‘esp-weather-station.php’! and others of your writings.

    Reply
  2. Good evening. That didn’t work. I got into Digital Ocean, but no hundred dollar credits were offered to me, i paid five dollars. I stop at the “Launch Console”, reports “incorrect login” (root). But today I’m done, continuing tomorrow. Good night.

    Reply
    • Please contact the DigitalOcean support team (in your account, there’s a contact meny), they’ll gladly help you access the console and see why the $100 credit is missing in your account. Regards,
      Rui

      Reply
  3. Rui / Sara,
    It would be useful if you presented a method for hosting the readers own mqtt type or linux service using an ESP32 as a web server and instructing how to create a DMZ on the users own router to save us having to fork-out for these expensive hosting services – to my pocket anything above £0 is out of my range. I beg borrow and steal (not really) to get ESP modules and components and just don’t have the monthly surplus to afford these.

    Just a thought
    Keep safe and Keep up the good work
    D

    Reply
  4. Hello Rui/Sara,
    It is glad to see this guide finally comes from you guys, I was waiting for this guide. I have implemented using your other guides to run Mosquitto MQTT Broker in my local network using a Raspberry Pi board and developed DHT22+ESP32 sensor to send data to the mosquito broker after the hosting it on Node-red Dashboard. Thanks for that.

    Can we use this method of hosting Mosquitto on the digital ocean for a commercial project? will this method satisfy the IoT security requirement?

    can we host the same mosquito broker on AWS? If so what might be the expected budget.

    Do you have any guide of implementing DHT22+ESP32 integration and publishing the data to the cloud server over HTTPS? If you are having can you please share the link with me.

    Thank you very much your help.

    Reply
    • I think so. Digital Ocean is a very reliable company that is used in many enterprises. The security mostly depends on how you configure your server.
      You should be able to also do it on AWS, but I’ve never tried it before.
      Thanks for asking!
      Rui

      Reply
  5. i like to install Mosquitto MQTT on blue host and send data from Mosquitto MQTT to mongo atlas cloud . any plugin needed for it .

    thanks

    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.