Skip to content

Tutorial

Node-RED, InfluxDB and Grafana: Log and Chart Sensor Data (Step by Step)

Store MQTT sensor readings in InfluxDB 2.x with Node-RED and chart them in Grafana: Docker Compose stack, data model, write flow, Flux queries, retention and fixes.

  • 5 min read
  • Updated November 2, 2026
Node-RED, InfluxDB and Grafana: Log and Chart Sensor Data (Step by Step)

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):

PartRoleDefault port
Mosquitto (MQTT)Receives readings from ESP32/ESP8266 boards1883
Node-REDValidates, reshapes and routes the data1880
InfluxDB 2.xStores timestamped readings in a bucket8086
GrafanaQueries InfluxDB and draws dashboards and alerts3000

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.

Data path: ESP32 publishes JSON over MQTT, Node-RED validates and writes it to InfluxDB 2.x, Grafana reads it with Flux

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.

config.yaml
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:

PartExampleRule of thumb
MeasurementenvironmentOne per kind of data, like a table name
Tags (indexed strings)device=esp32-01, room=labLow-cardinality labels you filter or group by
Fields (values)temperature_c=24.8, humidity_pct=51The numbers you chart. Not indexed
Timestampset by InfluxDB on arrivalOr send your own, with a matching precision

In line protocol, that point is:

Output
environment,device=esp32-01,room=lab temperature_c=24.8,humidity_pct=51

Three 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_c is first written as a float, a later integer or string write to the same field is rejected with HTTP 422. Send 24.0, not 24, 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:

config.json
{ "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:

TokenPermissionUsed by
nodered-writeWrite on bucket sensorsNode-RED
grafana-readRead on bucket sensorsGrafana

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:

script.js
// 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:

script.js
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

  1. Open http://<host>:3000 → Connections → Data sources → Add data source → InfluxDB.
  2. Set Query language: Flux, URL http://influxdb:8086, turn Basic auth off, then enter Organization home, the grafana-read token and Default Bucket sensors. Click Save & test; it should report the buckets it found.
  3. Dashboards → New → Add visualization, choose the InfluxDB source and paste this Flux query:
Output
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")
  1. Under Standard options → Unit, choose Temperature → Celsius (°C). Duplicate the panel and change the field to humidity_pct with unit Humidity (%H).
  2. 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 rateSuggested setup
A few sensors, every 10–60 sOne bucket, 30–365 days retention
Many sensors or every 1 sRaw bucket with 7–30 days, plus a downsampled bucket of 5-minute means kept for years
Long-term trends onlyAverage 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

SymptomLikely causeFix
HTTP 401 UnauthorizedWrong or missing token, or Bearer instead of TokenHeader must be Authorization: Token <token>; re-copy the token
HTTP 403 / "insufficient permissions"Token can't write to that bucketCreate a write token scoped to the right bucket
HTTP 404 "bucket not found" / "organization not found"Name typo or wrong orgCheck exact names (case-sensitive) under Buckets and About
HTTP 400 bad line protocolSpaces in tag values, missing field, quotes on numbersSanitise tags; check the string in a debug node
HTTP 422 field type conflictSame field written as float then integer/stringAlways write numbers the same way; or use a new field name
ECONNREFUSED from Node-REDUsing localhost inside DockerUse http://influxdb:8086 (the service name)
Grafana "Save & test" failsInfluxQL selected instead of Flux, or wrong org/tokenChoose Flux; use the read token and org name
Grafana panel says "No data"Time range too short or wrong measurement/fieldWiden to Last 24 hours; confirm the data in InfluxDB Data Explorer first
Points appear far in the past or futureYour own timestamps in the wrong precisionMatch precision to your timestamp (s, ms, ns) or let InfluxDB timestamp them
Chart dips to 0Failed sensor reads written as 0Keep 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

Official references: InfluxDB 2.x documentation, line protocol, node-red-contrib-influxdb and Grafana InfluxDB data source.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.