How to setup a Mosca Node.js MQTT broker service on Ubuntu 14.04

May 4, 2015

This article will cover installing Mosca Node.js MQTT standalone broker service along side Redis on Ubuntu 14.04. MQTT is a light weight publish-subscription messaging protocol for use on top of the TCP/IP.

MQTT is designed for connections with remote locations where network bandwidth is limited. The Pub/Sub messaging pattern requires a message broker which is what is covered in this article. The broker distributes messages to clients subscribers based on the topic of a message.

Step 0
Time Matters!

sudo apt-get update
sudo ntpdate
sudo apt-get install ntp

Step 1
Install Redis

sudo apt-get install build-essential
sudo apt-get install tcl8.5
gunzip -c redis-3.0.0.tar.gz | tar -xvf -
cd redis-3.0.0/
sudo make
sudo make install

Step 2
Start the Redis Server

cd utils/
sudo ./

Step 3
Install Mosca, and some helpful node packages

sudo apt-get update
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo apt-get install npm
sudo npm install debug
sudo npm install mosca bunyan -g
sudo npm install daemon

Step 4
Create your Mosca Node.js MQTT Broker Service mosca-app.js

var mosca = require('mosca')
var backjack = {
  type: 'redis',
  db: 12,
  port: 6379,
  return_buffers: true,
  host: "localhost"
var moscaSettings = {
  port: 1883,
  backend: backjack,
  persistence: {
    factory: mosca.persistence.Redis
var server = new mosca.Server(moscaSettings);
server.on('ready', setup);
server.on('clientConnected', function(client) {
    console.log('client connected',;     
server.on('published', function(packet, client) {
  console.log('Published', packet.payload);
function setup() {
  console.log('Mosca server is up and running')

Step 5
Start the Mosca Node.js MQTT Broker Service

node mosca-app.js

Step 6
Install MQTT Client For Testing

sudo npm install mqtt -g

Step 7
Write a MQTT Publishing Client client-pub.js

var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://localhost');
client.on('connect', function () {
  client.publish('presence', 'Hello!', {retain: false, qa: 1});

Step 8
Write a MQTT Subscription Client client-sub.js

var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://localhost');
client.on('connect', function () {
client.on('message', function (topic, message) {

Step 9
Open a New Terminal and Execute your MQTT Subscription Client client-sub.js

node client-sub.js

Step 10
Open a New Terminal and Execute your MQTT Publish Client client-pub.js

node client-pub.js

Successful Output From client-sub.js terminal


I will write a followup article on scaling Mosca soon for production.

Comments are closed.