Fast Way to Run a Secured Mosquitto MQTT Broker in the Docker

For example, you need to run the Eclipse Mosquitto MQTT Broker for a some simple IoT project. You need to be able to send the messages to the MQTT broker but you want to restrict the unnecessary access.

You just need to create a password file using the mosquitto_passwd utility and making some edits to the mosquitto.conf file to force password use.

To make this happen automatically in Docker we just could use a custom entrypoint:

#!/bin/ash

set -e

if ( [ -z "${MOSQUITTO_USERNAME}" ] || [ -z "${MOSQUITTO_PASSWORD}" ] ); then
  echo "MOSQUITTO_USERNAME or MOSQUITTO_PASSWORD not defined"
  exit 1
fi

# create mosquitto passwordfile
touch passwordfile
mosquitto_passwd -b passwordfile $MOSQUITTO_USERNAME $MOSQUITTO_PASSWORD

exec "[email protected]"

Just add a couple of lines to the Dockerfile:

FROM eclipse-mosquitto:1.4.12
COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"]

I have used the Docker Compose to pass the environment variables via .env file that will be used on the build.

version: '3'

services:

  # Eclipse Mosquitto MQTT Broker
  mosquitto:
    build: .
    environment:
      - MOSQUITTO_USERNAME=${MOSQUITTO_USERNAME}
      - MOSQUITTO_PASSWORD=${MOSQUITTO_PASSWORD}
    image: eclipse-mosquitto
    container_name: eclipse-mosquitto
    restart: always
    volumes:
      - ./config:/mosquitto/config:ro
      - ./data:/mosquitto/data
      - ./log:/mosquitto/log
    ports:
      - 1883:1883

Simply checking out the final source code and run it.