How to setup standalone mosquitto MQTT broker using docker-compose

docker-compose.yml

version: "3"

services:
  mosquitto:
    image: eclipse-mosquitto
    network_mode: host
    volumes:
      - ./conf:/mosquitto/conf
      - ./data:/mosquitto/data
      - ./log:/mosquitto/log

Now create conf/mosquitto.conf

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

listener 1883
## Authentication ##
# allow_anonymous false
password_file /mosquitto/conf/mosquitto.conf

Now create the first user using

docker-compose exec mosquitto mosquitto_passwd -c /mosquitto/conf/mosquitto.passwd mosquitto

You can optionally create more users using the -b (batch) flag instead of -c , supplying the password on the command line:

docker-compose exec mosquitto mosquitto_passwd -b /mosquitto/conf/mosquitto.passwd seconduser shoaCh3ohnokeathal6eeH2marei2o

Now start mosquitto using

docker-compose up

or create a systemd service to autostart it.

We are running mosquitto using network_mode: host. Mosquitto will, by default, listen on port 1883 (MQTT). You can configure more services using conf/mosquitto.conf, see this StackOverflow post for more info.