Any device that publishes {"t": 22.4, "h": 48.1} to home/<room>/climate ends up as a chart. Here the publisher is a Raspberry Pi with an SHT31 sensor, and the rest runs in Docker Compose on the home server.
The stack itself is not new. It has run in /srv/iot since 2021. This month I rebuilt it on a new SSD with current versions (InfluxDB 2, Grafana 13, Compose V2 file names), and this is the clean version of the files.
I use InfluxDB 2 because its Flux query language is what I already know. InfluxDB 3 does not support Flux, so check which major version you are installing. If you are starting fresh and do not care about Flux, SQLite or Postgres with a small script and Grafana is a fine choice at this scale, and easier to back up. I would still keep MQTT in front of it: the broker buffers, lets several consumers read the same data, and the payloads are tiny for microcontrollers.
Layout
I keep each stack in its own directory under /srv, which the Filesystem Hierarchy Standard reserves for data served by the machine:
/srv/iot/
├── compose.yaml
├── .env
├── mosquitto/
│ ├── config/mosquitto.conf
│ ├── config/passwd
│ └── data/
├── influxdb/data/
├── grafana/data/
└── telegraf/telegraf.conf
Data lives next to the compose file in bind mounts, not in named volumes. Then the whole stack, config and
data, is one directory, and the backup is one rsync of /srv.
compose.yaml
services:
mosquitto:
image: eclipse-mosquitto:2
restart: unless-stopped
ports: ["1883:1883"]
volumes:
- ./mosquitto/config:/mosquitto/config
- ./mosquitto/data:/mosquitto/data
influxdb:
image: influxdb:2
restart: unless-stopped
ports: ["8086:8086"]
environment:
DOCKER_INFLUXDB_INIT_MODE: setup
DOCKER_INFLUXDB_INIT_USERNAME: admin
DOCKER_INFLUXDB_INIT_PASSWORD: ${INFLUX_PASSWORD}
DOCKER_INFLUXDB_INIT_ORG: home
DOCKER_INFLUXDB_INIT_BUCKET: sensors
DOCKER_INFLUXDB_INIT_ADMIN_TOKEN: ${INFLUX_TOKEN}
volumes:
- ./influxdb/data:/var/lib/influxdb2
telegraf:
image: telegraf:1
restart: unless-stopped
depends_on: [mosquitto, influxdb]
environment:
INFLUX_TOKEN: ${INFLUX_TOKEN}
MQTT_PASSWORD: ${MQTT_TELEGRAF_PASSWORD}
volumes:
- ./telegraf/telegraf.conf:/etc/telegraf/telegraf.conf:ro
grafana:
image: grafana/grafana-oss:13
restart: unless-stopped
ports: ["3000:3000"]
volumes:
- ./grafana/data:/var/lib/grafana
The Grafana image runs as user ID 472, so its data directory must belong to that user:
sudo chown -R 472:472 /srv/iot/grafana/data.
.env holds the secrets and stays out of version control:
INFLUX_PASSWORD=change-me-long-and-random
INFLUX_TOKEN=change-me-too
MQTT_TELEGRAF_PASSWORD=change-me-as-well
Mosquitto
Since Mosquitto 2.0, the broker refuses remote connections unless you configure a listener and an authentication policy explicitly:
# mosquitto/config/mosquitto.conf
listener 1883
allow_anonymous false
password_file /mosquitto/config/passwd
persistence true
persistence_location /mosquitto/data/
One user per device and one for Telegraf, as on my old broker.
Create the file with the mosquitto_passwd inside the image. -c creates a new file, so use it only for
the first user:
docker compose run --rm mosquitto mosquitto_passwd -c /mosquitto/config/passwd telegraf
docker compose run --rm mosquitto mosquitto_passwd /mosquitto/config/passwd pi-study
Telegraf
Telegraf subscribes to MQTT and writes to InfluxDB. A hand-written subscriber would be a few lines, but then I own retries and batching. The topic parser turns the room name in the topic into a tag, so one config covers every room. This is why I put the identity in the topic and not in the payload:
[[inputs.mqtt_consumer]]
servers = ["tcp://mosquitto:1883"]
username = "telegraf"
password = "${MQTT_PASSWORD}"
topics = ["home/+/climate"]
data_format = "json"
name_override = "climate"
[[inputs.mqtt_consumer.topic_parsing]]
topic = "home/+/climate"
tags = "_/room/_"
[[outputs.influxdb_v2]]
urls = ["http://influxdb:8086"]
token = "${INFLUX_TOKEN}"
organization = "home"
bucket = "sensors"
Start everything:
cd /srv/iot && docker compose up -d
The publisher
I used an SHT31 here instead of a DHT22. It is on I2C, quicker to read, and more accurate on paper. On the Raspberry Pi with the SHT31 (enable I2C first with sudo raspi-config, then i2cdetect -y 1 should show address 0x44):
python3 -m venv ~/sensor-env && source ~/sensor-env/bin/activate
pip install adafruit-circuitpython-sht31d paho-mqtt
import json
import time
import adafruit_sht31d
import board
import paho.mqtt.client as mqtt
sensor = adafruit_sht31d.SHT31D(board.I2C())
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="pi-study")
client.username_pw_set("pi-study", "change-me")
client.connect("192.168.1.10", 1883) # the home server running the compose stack
client.loop_start()
while True:
payload = json.dumps({
"t": round(sensor.temperature, 2),
"h": round(sensor.relative_humidity, 1),
})
client.publish("home/study/climate", payload, qos=1)
time.sleep(30)
paho-mqtt 2.0 made the callback API version a required argument, which is why Client(...) starts with CallbackAPIVersion.VERSION2. Older tutorials omit it and fail on a current install.
Check that messages arrive:
docker compose exec mosquitto mosquitto_sub -u telegraf -P '...' -t 'home/#' -v
Query and chart
Open Grafana at port 3000, add an InfluxDB data source with query language Flux, URL http://influxdb:8086, organization home and your token. Then a panel query:
from(bucket: "sensors")
|> range(start: -24h)
|> filter(fn: (r) => r._measurement == "climate" and r._field == "t")
|> aggregateWindow(every: 5m, fn: mean, createEmpty: false)
Swap "t" for "h" for humidity. Because room is a tag, Grafana draws one line per room with no extra work.
Storage
Do not run this stack on an SD card for long. InfluxDB writes all the time, and SD cards wear out. I run it on the home server with an SSD. Since everything lives under /srv/iot, moving to a new machine is mostly one rsync. For a consistent copy of the database I still run influx backup before the nightly sync, as in the 2021 setup.
For a single sensor you only look at now and then, this whole stack is too much. A script that appends to a CSV file is enough.