Virtual Modbus Docker Lab
In this lab you build the full IIoT pipeline from IIoT Start Here with no hardware:
+------------------+ Modbus TCP +------------------+ SQL INSERT +------------------+ SQL +----------+| plc-sim | <-----------> | poller | -------------> | timescaledb | <------- | grafana || pymodbus server | port 5020 | pymodbus client | psycopg2 | hypertable | | :3000 || float32 temp, | (internal) | decode float32 | | readings(time, | | panels || rpm, counter | | every 2 s | | tag, value) | | |+------------------+ +------------------+ +------------------+ +----------+ all four containers share one Docker network created by ComposeWhat you need: Docker Engine with the Compose plugin (docker compose version should work), about 2 GB of free RAM and ports 3000, 5020 and 5432 free on the host.
Register map of the virtual PLC
Section titled “Register map of the virtual PLC”| Address (0-based) | Registers | Type | Meaning |
|---|---|---|---|
| 0-1 | 2 | float32, big-endian (ABCD, high word first) | temperature_c, sine wave around 25 C plus noise |
| 2 | 1 | uint16 | rpm, around 1450 |
| 3 | 1 | uint16 | counter, increments every second, wraps at 65535 |
Float32 spread across two registers is the classic source of confusion. If your values look absurd (for example 1.2e-38 or huge numbers), paste the two raw register values into the Modbus Float Converter and try the other word/byte orders.
Project tree
Section titled “Project tree”modbus-lab/├── docker-compose.yml├── db/│ └── init.sql├── plc-sim/│ ├── Dockerfile│ ├── requirements.txt│ └── server.py├── poller/│ ├── Dockerfile│ ├── requirements.txt│ └── poller.py└── grafana/ └── provisioning/ └── datasources/ └── timescaledb.ymlCreate it:
mkdir -p modbus-lab/{db,plc-sim,poller,grafana/provisioning/datasources}cd modbus-labFile contents
Section titled “File contents”docker-compose.yml
Section titled “docker-compose.yml”services: timescaledb: image: timescale/timescaledb:latest-pg16 container_name: lab-timescaledb environment: POSTGRES_USER: lab # LAB DEFAULT POSTGRES_PASSWORD: labpass # LAB DEFAULT - change for anything real POSTGRES_DB: iiot ports: - "5432:5432" volumes: - tsdata:/var/lib/postgresql/data - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro healthcheck: test: ["CMD-SHELL", "pg_isready -U lab -d iiot"] interval: 5s timeout: 5s retries: 20
plc-sim: build: ./plc-sim container_name: lab-plc-sim ports: - "5020:5020" restart: unless-stopped
poller: build: ./poller container_name: lab-poller environment: PLC_HOST: plc-sim PLC_PORT: "5020" UNIT_ID: "1" POLL_SECONDS: "2" PGHOST: timescaledb PGPORT: "5432" PGUSER: lab PGPASSWORD: labpass PGDATABASE: iiot depends_on: timescaledb: condition: service_healthy plc-sim: condition: service_started restart: unless-stopped
grafana: image: grafana/grafana:latest container_name: lab-grafana environment: GF_SECURITY_ADMIN_USER: admin # LAB DEFAULT GF_SECURITY_ADMIN_PASSWORD: admin # LAB DEFAULT ports: - "3000:3000" volumes: - grafanadata:/var/lib/grafana - ./grafana/provisioning:/etc/grafana/provisioning:ro depends_on: - timescaledb restart: unless-stopped
volumes: tsdata: grafanadata:db/init.sql
Section titled “db/init.sql”CREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE IF NOT EXISTS readings ( time TIMESTAMPTZ NOT NULL, tag TEXT NOT NULL, value DOUBLE PRECISION NOT NULL);
SELECT create_hypertable('readings', 'time', if_not_exists => TRUE);
CREATE INDEX IF NOT EXISTS readings_tag_time_idx ON readings (tag, time DESC);The init script runs only the first time the data volume is created. To re-run it, remove the volume (see clean-up).
plc-sim/requirements.txt
Section titled “plc-sim/requirements.txt”pymodbus==3.6.9plc-sim/Dockerfile
Section titled “plc-sim/Dockerfile”FROM python:3.11-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY server.py .CMD ["python", "-u", "server.py"]plc-sim/server.py
Section titled “plc-sim/server.py”import asyncioimport mathimport randomimport structimport time
from pymodbus.datastore import ( ModbusSequentialDataBlock, ModbusServerContext, ModbusSlaveContext,)from pymodbus.server import StartAsyncTcpServer
PORT = 5020
def float_to_regs(value: float): """Encode float32 big-endian into two 16-bit registers [high, low].""" hi, lo = struct.unpack(">HH", struct.pack(">f", value)) return [hi, lo]
async def updater(context): """Update the holding registers once per second, like a live process.""" start = time.time() counter = 0 while True: t = time.time() - start temperature = 25.0 + 5.0 * math.sin(t / 30.0) + random.uniform(-0.2, 0.2) rpm = int(1450 + 50 * math.sin(t / 10.0) + random.randint(-5, 5)) counter = (counter + 1) % 65536 values = float_to_regs(temperature) + [rpm, counter] # function code 3 = holding registers, start address 0 context[0].setValues(3, 0, values) await asyncio.sleep(1)
async def main(): # zero_mode=True makes request address 0 map to datablock index 0 store = ModbusSlaveContext( hr=ModbusSequentialDataBlock(0, [0] * 100), zero_mode=True, ) # single=True: every unit/slave id answers from this one store context = ModbusServerContext(slaves=store, single=True) asyncio.create_task(updater(context)) print(f"Virtual PLC listening on 0.0.0.0:{PORT}", flush=True) await StartAsyncTcpServer(context=context, address=("0.0.0.0", PORT))
if __name__ == "__main__": asyncio.run(main())poller/requirements.txt
Section titled “poller/requirements.txt”pymodbus==3.6.9psycopg2-binary==2.9.9poller/Dockerfile
Section titled “poller/Dockerfile”FROM python:3.11-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY poller.py .CMD ["python", "-u", "poller.py"]poller/poller.py
Section titled “poller/poller.py”import osimport structimport time
import psycopg2from pymodbus.client import ModbusTcpClient
PLC_HOST = os.environ.get("PLC_HOST", "plc-sim")PLC_PORT = int(os.environ.get("PLC_PORT", "5020"))UNIT_ID = int(os.environ.get("UNIT_ID", "1"))POLL_SECONDS = float(os.environ.get("POLL_SECONDS", "2"))
def connect_db(): """Retry until the database accepts connections.""" while True: try: conn = psycopg2.connect( host=os.environ["PGHOST"], port=os.environ.get("PGPORT", "5432"), user=os.environ["PGUSER"], password=os.environ["PGPASSWORD"], dbname=os.environ["PGDATABASE"], ) conn.autocommit = True print("Connected to TimescaleDB", flush=True) return conn except psycopg2.OperationalError as exc: print(f"DB not ready ({exc}); retrying in 3 s", flush=True) time.sleep(3)
def decode_float32_be(hi: int, lo: int) -> float: """Two registers -> float32, big-endian word order (ABCD).""" return struct.unpack(">f", struct.pack(">HH", hi, lo))[0]
def main(): db = connect_db() client = ModbusTcpClient(PLC_HOST, port=PLC_PORT)
while True: try: if not client.connected and not client.connect(): print("PLC not reachable; retrying", flush=True) time.sleep(3) continue
# read 4 registers starting at address 0 (`slave` is the unit id keyword in 3.6.x) rr = client.read_holding_registers(0, 4, slave=UNIT_ID) if rr.isError(): print(f"Modbus error: {rr}", flush=True) client.close() time.sleep(POLL_SECONDS) continue
regs = rr.registers temperature = decode_float32_be(regs[0], regs[1]) rows = [ ("temperature_c", temperature), ("rpm", float(regs[2])), ("counter", float(regs[3])), ] with db.cursor() as cur: cur.executemany( "INSERT INTO readings (time, tag, value) VALUES (now(), %s, %s)", rows, ) print(f"temperature_c={temperature:.2f} rpm={regs[2]} counter={regs[3]}", flush=True) except psycopg2.Error as exc: print(f"DB error: {exc}; reconnecting", flush=True) db = connect_db() except Exception as exc: # network glitches, decode errors print(f"Poll error: {exc}", flush=True) client.close() time.sleep(POLL_SECONDS)
if __name__ == "__main__": main()grafana/provisioning/datasources/timescaledb.yml
Section titled “grafana/provisioning/datasources/timescaledb.yml”apiVersion: 1datasources: - name: TimescaleDB type: grafana-postgresql-datasource uid: timescaledb-lab access: proxy url: timescaledb:5432 user: lab isDefault: true jsonData: database: iiot sslmode: disable postgresVersion: 1600 timescaledb: true secureJsonData: password: labpassIf Grafana reports an unknown datasource type, your version uses the older id: change type to postgres. Alternatively delete this file and add the datasource manually (see below).
Run it
Section titled “Run it”docker compose up -d --builddocker compose psdocker compose logs -f pollerWithin a few seconds the poller log should show lines such as temperature_c=25.31 rpm=1452 counter=14. Press Ctrl+C to leave the log view (the stack keeps running). Other useful logs:
docker compose logs --tail=50 plc-simdocker compose logs --tail=50 timescaledbdocker compose logs --tail=50 grafanaVerify the data with SQL
Section titled “Verify the data with SQL”Open a psql shell inside the database container:
docker compose exec timescaledb psql -U lab -d iiotCount rows per tag:
SELECT tag, count(*) FROM readings GROUP BY tag;Last 10 temperature values:
SELECT time, valueFROM readingsWHERE tag = 'temperature_c'ORDER BY time DESCLIMIT 10;One-minute averages with time_bucket:
SELECT time_bucket('1 minute', time) AS minute, round(avg(value)::numeric, 2) AS avg_temp, min(value) AS min_temp, max(value) AS max_tempFROM readingsWHERE tag = 'temperature_c' AND time > now() - interval '30 minutes'GROUP BY minuteORDER BY minute DESC;Quit psql with \q. Check the hypertable exists with SELECT hypertable_name FROM timescaledb_information.hypertables;.
Build a Grafana panel
Section titled “Build a Grafana panel”- Browse to
http://localhost:3000and log in withadmin/admin(you will be asked to change it; do so). - Check Connections > Data sources. If TimescaleDB is missing, click Add data source, choose PostgreSQL, and enter host
timescaledb:5432, databaseiiot, userlab, passwordlabpass, TLS/SSL modedisable, and enable the TimescaleDB option. Save and test. - Create a dashboard, add a Time series visualisation, switch the query editor to Code, set format to Time series and paste:
SELECT $__timeGroupAlias("time", $__interval), avg(value) AS "temperature_c"FROM readingsWHERE $__timeFilter("time") AND tag = 'temperature_c'GROUP BY 1ORDER BY 1- Set the time range to “Last 15 minutes” and refresh to 5s. Add a second panel with
tag = 'rpm', and an alert rule if you want to practise thresholds (for example temperature above 29).
Experiments
Section titled “Experiments”- Query the PLC directly from your host with any Modbus client against
localhost:5020, holding registers, address 0, count 2, then check the pair in the Modbus Float Converter. - Change the encoding in
server.pyto little-endian word order ([lo, hi]) and see how the poller output breaks until you also swap inpoller.py. This is exactly what happens with mismatched vendors. - Add a gateway stage: publish each reading to an MQTT broker and design topics with the MQTT Topic Tester.
- Plan how this would sit on a real plant network using the Subnet and VLAN Planner.
- Generate similar stack scaffolding with the Script Stack Generator.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Likely cause | Fix |
|---|---|---|
port is already allocated on up |
Host already uses 3000, 5020 or 5432 (local Postgres is common) | Change the left side of the port mapping, e.g. "5433:5432" |
Poller logs DB not ready forever |
Wrong credentials, or old volume created with different password | docker compose down -v then up -d --build |
relation "readings" does not exist |
init.sql did not run (volume already existed) |
docker compose down -v, then bring the stack up again |
PLC not reachable |
plc-sim crashed or still starting |
docker compose logs plc-sim; the poller retries on its own |
TypeError ... unexpected keyword argument 'slave' |
Different pymodbus version installed | Keep pymodbus==3.6.9; rebuild with --build --no-cache |
| Temperature looks like garbage | Word/byte order mismatch | Check with the Modbus Float Converter |
| Grafana “unknown datasource type” | Older/newer Grafana plugin id | Use type: postgres, or add the datasource manually |
| Grafana “No data” | Time range or tag name mismatch | Set range to last 15 min; run the SQL in psql to confirm rows |
| Grafana cannot connect to database | Used localhost as host |
Inside Docker use timescaledb:5432, not localhost |
Clean up
Section titled “Clean up”Stop the stack but keep the data:
docker compose downRemove containers, volumes (all stored readings and Grafana settings) and the built images:
docker compose down -v --rmi localOptional: reclaim space from unused Docker objects with docker system prune (it asks for confirmation and removes all unused containers, networks and dangling images system-wide).
Next steps
Section titled “Next steps”Continue with MQTT and the IoT pillar, harden what you built with Cybersecurity Start Here, and see more tooling in /tools/. Port numbers for the protocols used here are in the Industrial Ports and Protocols cheat sheet.