87 lines
2.6 KiB
YAML
87 lines
2.6 KiB
YAML
services:
|
|
mosquitto:
|
|
image: eclipse-mosquitto:2
|
|
container_name: ${CONTAINER_NAME:-mosquitto}
|
|
restart: unless-stopped
|
|
|
|
environment:
|
|
TZ: ${TZ:-Europe/Berlin}
|
|
MQTT_HOSTNAME: ${MQTT_HOSTNAME:-mqtt.local}
|
|
MQTT_USER: ${MQTT_USER:-mqttuser}
|
|
MQTT_TLS_PORT: ${MQTT_TLS_PORT:-8883}
|
|
dns:
|
|
- ${DNS_SERVER}
|
|
volumes:
|
|
- ${VOLUME_ROOT:-.}/config:/mosquitto/config
|
|
- ${VOLUME_ROOT:-.}/data:/mosquitto/data
|
|
- ${VOLUME_ROOT:-.}/log:/mosquitto/log
|
|
|
|
# Self-signed TLS certs (writeable)
|
|
- ${VOLUME_ROOT:-.}/tls:/mosquitto/tls
|
|
|
|
# System CA store (read-only)
|
|
- /etc/ssl/certs:/etc/ssl/certs:ro
|
|
|
|
ports:
|
|
- "${MQTT_TLS_PORT:-8883}:8883"
|
|
|
|
command: >
|
|
sh -c '
|
|
TLS_DIR=/mosquitto/tls;
|
|
CONF=/mosquitto/config/mosquitto.conf;
|
|
PASSWD=/mosquitto/config/passwd;
|
|
|
|
mkdir -p "$TLS_DIR";
|
|
|
|
echo "=== Checking self-signed certificates ===";
|
|
|
|
if [ ! -f "$TLS_DIR/server.crt" ]; then
|
|
echo "Generating self-signed certificates in $TLS_DIR...";
|
|
openssl genrsa -out $TLS_DIR/ca.key 4096;
|
|
openssl req -x509 -new -nodes -key $TLS_DIR/ca.key -sha256 -days 3650 \
|
|
-out $TLS_DIR/ca.crt -subj "/CN=LocalMQTT-CA";
|
|
|
|
openssl genrsa -out $TLS_DIR/server.key 4096;
|
|
openssl req -new -key $TLS_DIR/server.key -out $TLS_DIR/server.csr \
|
|
-subj "/CN=$MQTT_HOSTNAME";
|
|
|
|
openssl x509 -req -in $TLS_DIR/server.csr -CA $TLS_DIR/ca.crt \
|
|
-CAkey $TLS_DIR/ca.key -CAcreateserial \
|
|
-out $TLS_DIR/server.crt -days 3650 -sha256;
|
|
else
|
|
echo "Self-signed certificates already exist in $TLS_DIR.";
|
|
fi;
|
|
|
|
echo "=== Checking mosquitto.conf ===";
|
|
|
|
if [ ! -f "$CONF" ]; then
|
|
echo "Generating default mosquitto.conf at $CONF...";
|
|
cat <<EOF > $CONF
|
|
listener ${MQTT_TLS_PORT:-8883}
|
|
protocol mqtt
|
|
cafile /mosquitto/tls/ca.crt
|
|
certfile /mosquitto/tls/server.crt
|
|
keyfile /mosquitto/tls/server.key
|
|
allow_anonymous false
|
|
password_file /mosquitto/config/passwd
|
|
EOF
|
|
else
|
|
echo "Existing mosquitto.conf found at $CONF.";
|
|
fi;
|
|
|
|
echo "=== Checking user ===";
|
|
|
|
if [ ! -f "$PASSWD" ]; then
|
|
echo "Generating random password for user: $MQTT_USER";
|
|
RANDOM_PASS=$(openssl rand -base64 32);
|
|
echo "Generated password (save this!):";
|
|
echo "$RANDOM_PASS";
|
|
mosquitto_passwd -c -b "$PASSWD" "$MQTT_USER" "$RANDOM_PASS";
|
|
else
|
|
echo "Password file exists at $PASSWD — skipping user creation.";
|
|
fi;
|
|
|
|
echo "=== Starting Mosquitto ===";
|
|
mosquitto -c $CONF
|
|
'
|