[Part II] IoT with docker-compose

Perfect is the enemy of good. That’s the case with the IoT backend system that we described part I. In our previous post, we went step by step through the procedure of setting up:

  • MQTT server to listen in incoming topics, e.g. sensors,
  • Influx database to store time series of sensor data,
  • Telegraf to connect them, as a server agent

Great. Now, there is an alternative way to do that again with docker. Compose is a tool for defining and running multi-container docker applications. We just need to write a YAML file to configure your application’s services. Let’s how this looks like for our application:

version: "3.5"
services:
  mosquitto:
    image: eclipse-mosquitto:latest
    hostname: mosquitto
    container_name: mosquitto
    restart: always
    ports: 
      - "1883:1883"
  influxdb:
    image: influxdb:latest
    hostname: influxdb
    container_name: influxdb
    restart: always
    depends_on: 
      - mosquitto  
    ports:
      - "8086:8086"
    volumes:
      - influxdb-storage:/var/lib/influxdb
    environment:
      - INFLUXDB_DB=sensors
      - INFLUXDB_USER=telegraf-username
      - INFLUXDB_PASSWORD=telegraf-password
  telegraf:
    image: telegraf:latest
    hostname: telegraf
    container_name: telegraf
    restart: always
    depends_on:
      - influxdb
    ports:
      - "5050:5050"
    volumes:
      - ./telegraf/telegraf.conf:/etc/telegraf/telegraf.conf:ro
volumes:
  influxdb-storage: {}

and this our iot.yml file. Following, we realise that the steps are the same as the commands, we were passing in the terminal. No surprise. Then in the local telegraf folder, we include the configuration file for the telegraf:

[[inputs.mqtt_consumer]]
  servers = ["tcp://mosquitto:1883"]
  topics = ["sensors"]
  data_format = "influx"

[[outputs.influxdb]]
  urls = ["http://influxdb:8086"]
  database = "sensors"
  skip_database_creation = true
  username = "telegraf-username"
  password = "telegraf-password" 
  user_agent = "telegraf"

and this is the telegraf.conf file.

If you want to see the complete picture, please visit the relevant GitHub repository. Now, if you type in your terminal the following command,

docker-compose -f iot.yml up

you will see all the components becoming alive and functional!