Mosquitto MQTT

I’m currently running multiple instances of Mosquitto MQTT server

Running as docker container

Easily set up, not polluting guest’s filesystem… Inpired by https://www.laub-home.de/wiki/Eclipse_Mosquitto_Secure_MQTT_Broker_Docker_Installation

Docker file could be like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
services:q
  mosquitto:
    image: eclipse-mosquitto:2.0
    restart: always
    volumes:
      - "./mqtt/conf:/mosquitto/config"
      - mosquitto_data:/mosquitto/data
      - mosquitto_log:/mosquitto/log
    ports:
      - ${MQTT_PORT}:1883
      - ${MQTT_TLS_PORT}:8883
    environment:
      - TZ
volumes:
  mosquitto_data:
  mosquitto_log:
  

having MQTT_PORT and MQTT_TLS_PORT being defined in a .env file

In the directory where the docker-compose.yml file is located, create a subdirectory structure :

  • mqtt/conf, containing mosquitto.conf
  • mqtt/conf/certs, containing the SSL certificates in case you want to activate TLS. You can for example request one from let’s encrypt

the mosquitto.conf file would then look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
listener 1883
listener 8883

persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log

allow_anonymous false
password_file /mosquitto/config/mosquitto.passwd

cafile /mosquitto/config/certs/ca.crt
certfile /mosquitto/config/certs/server.crt
keyfile /mosquitto/config/certs/server.key
tls_version tlsv1.2

Configuring passwords for users

Initial user docker-compose exec mosquitto mosquitto_passwd -c /mosquitto/config/mosquitto.passwd <username>

Further user docker-compose exec mosquitto mosquitto_passwd -b /mosquitto/config/mosquitto.passwd user1

Testing the setup

Install the mosquitto-clients package

Reading messages

Subscribe with mosquitto_sub -v -t '#' -u <username> -P <password> -h localhost

The -v option prints additionally the topic next to the data

Sending messages

Publish with mosquitto_pub -p 1883 -u <username> -P <password> -t 'my/topic/to/publish' -h localhost -m '<put message here'

Where the message can be anything from an integer, float, string, or more complex JSON structures.

Server to server bridge

It is possible to have a mosquitto server subscribe the topics published on another one. This way, all messages are collected on one single place, and they can be fetched centrally.

For this, add this snippet to /etc/mosquitto/conf.d/remote.conf on the receiving server:

1
2
3
4
5
6
7
8
connection <choose ID>
address <enter IP or name>:1883
remote_password <enter password>
remote_username <enter user>
remote_clientid <choose one>

#topic # out 0
topic # in 0

topic syntax is topic <topic pattern> <direction> <QOS> <local prefix/remote prefix>