Quick answer: to log sensor data with Node-RED, InfluxDB and Grafana, run all three (the Docker Compose file below starts them in one command). In InfluxDB 2.x create a bucket (for example sensors) and a write token. In Node-RED, take your MQTT readings through a Function node that checks the numbers, then write them with the influxdb out node (or an HTTP Request to /api/v2/write). In Grafana add an InfluxDB data source with Flux, give it a read token, and build a time-series panel with a short Flux query. Readings then show up as a chart within seconds and stay stored for as long as your retention setting allows.
A live gauge answers "what is the reading now?" A time-series database answers "what happened overnight, last week, since I moved the sensor?" That is the job of this stack, often called MING (MQTT, InfluxDB, Node-RED, Grafana):
| Part | Role | Default port |
|---|---|---|
| Mosquitto (MQTT) | Receives readings from ESP32/ESP8266 boards | 1883 |
| Node-RED | Validates, reshapes and routes the data | 1880 |
| InfluxDB 2.x | Stores timestamped readings in a bucket | 8086 |
| Grafana | Queries InfluxDB and draws dashboards and alerts | 3000 |
This guide uses InfluxDB 2.x (the Flux / /api/v2 version most tutorials and the Node-RED node target). InfluxDB 1.x and 3.x use different setup and query languages; if you install one of those, follow its own docs for the database parts.
1. Start InfluxDB, Grafana and Node-RED with Docker Compose
The fastest reliable setup on a Raspberry Pi 4/5 (64-bit OS), a Linux PC or Windows with Docker Desktop. Save as docker-compose.yml, change the passwords and token, then run docker compose up -d.
services:
influxdb:
image: influxdb:2.7
ports: ["8086:8086"]
volumes: ["influxdb-data:/var/lib/influxdb2"]
environment:
DOCKER_INFLUXDB_INIT_MODE: setup
DOCKER_INFLUXDB_INIT_USERNAME: admin
DOCKER_INFLUXDB_INIT_PASSWORD: change-this-password
DOCKER_INFLUXDB_INIT_ORG: home
DOCKER_INFLUXDB_INIT_BUCKET: sensors
DOCKER_INFLUXDB_INIT_RETENTION: 30d
DOCKER_INFLUXDB_INIT_ADMIN_TOKEN: change-this-long-random-admin-token
restart: unless-stopped
grafana:
image: grafana/grafana-oss
ports: ["3000:3000"]
volumes: ["grafana-data:/var/lib/grafana"]
restart: unless-stopped
nodered:
image: nodered/node-red
ports: ["1880:1880"]
volumes: ["nodered-data:/data"]
restart: unless-stopped
volumes:
influxdb-data:
grafana-data:
nodered-data:Inside this Compose network the containers reach each other by service name, so Node-RED and Grafana use http://influxdb:8086, not localhost. Already running Node-RED and Mosquitto natively (Node-RED on a Pi, Mosquitto on a Pi)? Drop the nodered service and use the Pi's IP address with port 8086 instead.
The INIT_ variables only apply on the very first start with an empty volume. Grafana's first login is admin / admin, and it asks you to change it.
2. Plan the data before wiring nodes
InfluxDB stores each reading as a point with four parts:
| Part | Example | Rule of thumb |
|---|---|---|
| Measurement | environment | One per kind of data, like a table name |
| Tags (indexed strings) | device=esp32-01, room=lab | Low-cardinality labels you filter or group by |
| Fields (values) | temperature_c=24.8, humidity_pct=51 | The numbers you chart. Not indexed |
| Timestamp | set by InfluxDB on arrival | Or send your own, with a matching precision |
In line protocol, that point is:
environment,device=esp32-01,room=lab temperature_c=24.8,humidity_pct=51Three rules save you pain later:
- Never put changing values in tags (timestamps, message IDs, readings). Every unique tag combination creates a new series, and unbounded series slow InfluxDB down.
- Keep a field's type fixed. If
temperature_cis first written as a float, a later integer or string write to the same field is rejected with HTTP 422. Send24.0, not24, or let the Function node convert. - Don't write 0 for a failed read. Skip the point, so Grafana shows a gap instead of a fake dip.
The ESP32 side just publishes JSON, for example to solderhub/lab/esp32-01/environment:
{ "device": "esp32-01", "temperature_c": 24.8, "humidity_pct": 51.0 }(See ESP32 MQTT publish and subscribe for the firmware side.)
3. Create tokens in InfluxDB
Open http://<host>:8086 and sign in as the admin user from the Compose file. Then go to Load Data → API Tokens → Generate API Token → Custom API Token and create two:
| Token | Permission | Used by |
|---|---|---|
nodered-write | Write on bucket sensors | Node-RED |
grafana-read | Read on bucket sensors | Grafana |
Copy each token when it's shown: InfluxDB displays it only once. Don't use the admin token in Node-RED or Grafana, and don't paste tokens into flows you export or share. Check your org name under About (it is home in the Compose example).
To change how long data is kept, go to Load Data → Buckets → sensors → Settings. Thirty days of one reading every 10 seconds from a few sensors is tiny; years of 1-second data from many devices is not, so choose deliberately.
4. Build the Node-RED flow
Option A (recommended): the influxdb nodes. In Node-RED, open Menu → Manage palette → Install, search node-red-contrib-influxdb and install it. Then build:
mqtt in (topic solderhub/lab/+/environment, output a parsed JSON object) → function (below) → influxdb out
Configure the influxdb out node: add a server with Version 2.0, URL http://influxdb:8086 (or http://<pi-ip>:8086) and the nodered-write token; then set Organization home, Bucket sensors, Measurement environment, Time Precision Milliseconds.
The Function node rejects bad readings and builds the [fields, tags] array the influxdb out node expects:
// Input: msg.payload = { device, temperature_c, humidity_pct }
const p = msg.payload;
const t = Number(p && p.temperature_c);
const h = Number(p && p.humidity_pct);
// Reject missing or impossible values instead of logging zeros
if (!Number.isFinite(t) || !Number.isFinite(h) || t < -40 || t > 85 || h < 0 || h > 100) {
node.warn("Rejected sensor payload: " + JSON.stringify(p));
return null;
}
// Restrict tag values to safe characters (no spaces, commas or '=')
const device = String(p.device || "unknown").replace(/[^A-Za-z0-9_-]/g, "_");
msg.payload = [
{ temperature_c: t, humidity_pct: h }, // fields (numbers)
{ device: device } // tags (strings)
];
return msg;Option B: plain HTTP Request (no extra nodes). Replace the last two lines of the Function with line protocol and headers, then send it with an http request node set to POST and the URL http://influxdb:8086/api/v2/write?org=home&bucket=sensors&precision=s:
msg.payload = `environment,device=${device} temperature_c=${t},humidity_pct=${h}`;
msg.headers = {
"Authorization": "Token " + env.get("INFLUX_TOKEN"),
"Content-Type": "text/plain; charset=utf-8"
};
return msg;Set INFLUX_TOKEN as an environment variable on the Node-RED host (or on the flow tab's Environment Variables settings) so it doesn't end up in exported flow JSON. A successful write returns HTTP 204 (no content); connect a debug node showing msg.statusCode to see it.
Check the data arrived before touching Grafana: in InfluxDB open Data Explorer, pick bucket sensors → measurement environment → field temperature_c, and click Submit.
5. Chart it in Grafana
- Open
http://<host>:3000→ Connections → Data sources → Add data source → InfluxDB. - Set Query language: Flux, URL
http://influxdb:8086, turn Basic auth off, then enter Organizationhome, thegrafana-readtoken and Default Bucketsensors. Click Save & test; it should report the buckets it found. - Dashboards → New → Add visualization, choose the InfluxDB source and paste this Flux query:
from(bucket: "sensors")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r._measurement == "environment" and r._field == "temperature_c")
|> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
|> yield(name: "mean")- Under Standard options → Unit, choose Temperature → Celsius (°C). Duplicate the panel and change the field to
humidity_pctwith unit Humidity (%H). - Set the time range (top right) to Last 6 hours and save the dashboard.
aggregateWindow averages points to fit the panel width, so a 30-day view stays fast. Grafana has no point-and-click builder for Flux; the easiest way to write new queries is to build them in InfluxDB's Data Explorer, click Script Editor, and paste the result into Grafana (replacing the fixed times with v.timeRangeStart / v.timeRangeStop). To show several devices on one panel, remove the device filter: each device tag becomes its own line.
6. Retention, downsampling and data quality
| Data rate | Suggested setup |
|---|---|
| A few sensors, every 10–60 s | One bucket, 30–365 days retention |
| Many sensors or every 1 s | Raw bucket with 7–30 days, plus a downsampled bucket of 5-minute means kept for years |
| Long-term trends only | Average in Node-RED (e.g. a 1-minute mean) before writing |
For downsampling, create a second bucket (sensors_5m) and an InfluxDB Task that runs every 5 minutes, using aggregateWindow(every: 5m, fn: mean) and to(bucket: "sensors_5m"). Show device availability separately from readings: a "last seen" stat panel, or MQTT Last Will messages, tells you a sensor died, whereas a flat line or a gap only hints at it.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| HTTP 401 Unauthorized | Wrong or missing token, or Bearer instead of Token | Header must be Authorization: Token <token>; re-copy the token |
| HTTP 403 / "insufficient permissions" | Token can't write to that bucket | Create a write token scoped to the right bucket |
| HTTP 404 "bucket not found" / "organization not found" | Name typo or wrong org | Check exact names (case-sensitive) under Buckets and About |
| HTTP 400 bad line protocol | Spaces in tag values, missing field, quotes on numbers | Sanitise tags; check the string in a debug node |
| HTTP 422 field type conflict | Same field written as float then integer/string | Always write numbers the same way; or use a new field name |
ECONNREFUSED from Node-RED | Using localhost inside Docker | Use http://influxdb:8086 (the service name) |
| Grafana "Save & test" fails | InfluxQL selected instead of Flux, or wrong org/token | Choose Flux; use the read token and org name |
| Grafana panel says "No data" | Time range too short or wrong measurement/field | Widen to Last 24 hours; confirm the data in InfluxDB Data Explorer first |
| Points appear far in the past or future | Your own timestamps in the wrong precision | Match precision to your timestamp (s, ms, ns) or let InfluxDB timestamp them |
| Chart dips to 0 | Failed sensor reads written as 0 | Keep the validation in the Function node |
FAQ
Do I need InfluxDB to make charts in Node-RED? No. The Dashboard chart widget keeps a short in-memory history, which is fine for "the last hour". Use InfluxDB when you need history that survives restarts, long time ranges, or Grafana's analysis and alerting.
Can I run Node-RED, InfluxDB and Grafana on a Raspberry Pi? Yes. A Pi 4 or Pi 5 with the 64-bit OS handles a home sensor network comfortably. Use an SSD or a good SD card, because databases write constantly.
InfluxDB 1.x, 2.x or 3.x? 2.x is what most Node-RED and Grafana tutorials (including this one) use, with Flux and API tokens. 1.x uses InfluxQL and usernames. 3.x is a newer engine with SQL and a different API. Pick one and follow its own docs; the Node-RED validation pattern stays the same.
Flux or InfluxQL in Grafana? Flux works natively with InfluxDB 2.x and is used here. InfluxQL on 2.x needs extra DBRP mappings, so only choose it if you already know InfluxQL.
How often should I log readings? Every 10–60 seconds is plenty for room temperature and humidity. Faster rates mostly add storage without adding information.
Next steps
- Get readings flowing first: ESP32 DHT11 + BMP280 live dashboard with Node-RED.
- MQTT basics in Node-RED: Node-RED with Mosquitto: publish and subscribe.
- Add buttons and gauges next to Grafana: Node-RED Dashboard 2.0 setup.
- Make flows survive bad data: Reliable Node-RED flows with subflows and Catch nodes.
- Lock the stack down: Secure Node-RED with HTTPS, MQTT TLS and backups.
Official references: InfluxDB 2.x documentation, line protocol, node-red-contrib-influxdb and Grafana InfluxDB data source.




