Automatically provisioning Grafana datasources and dashboards using docker

I have been experimenting with using Grafana to visualize time-series data recently, and it so far it has been quite a nice experience. One problem that I kept running in, was that I manually created and tweaked a dashboard in the Grafana UI, but when I destroyed and re-build the docker-container, the dashboard was gone. Of course, this was not unexpected, since I wasn’t persisting anything Grafana related outside off its docker-container. But until today I hadn’t taken the time to look into solving this issue.

The solution is pretty simple. This is what I did:

  • create a Dockerfile
  • create a datasources and dashboards folder next to the Dockerfile
  • export the dashboard from the Grafana UI as a JSON-file (in this example that’s the my-main-dashboard.json file)
  • create a grafana datasource-config file (in this example that’s the postgres.yml) and place it in the datasources-folder
  • ADD those folders to the image (see the Dockerfile below)

This is what the folder with the Dockfile looks like:

├── Dockerfile
├── dashboards
│   └── dashboard.yml            <-- you have to create the yml-file by hand, see the grafana docs 
│   └── my-main-dashboard.json   <-- you can export this from the grafana UI
│   └── second-dashboard.json
│   └── ...
└── datasources
    └── postgres.yml             <-- again, create this by hand, see the docs
    └── another-datasource.yml
    └── ...

And here are the contents of the Dockerfile:

FROM grafana/grafana:8.0.4      <-- you should change this to the version you need

ADD ./dashboards/ /etc/grafana/provisioning/dashboards/
ADD ./datasources/ /etc/grafana/provisioning/datasources/

And the dashboards.yml:

apiVersion: 1

- name: 'default'
  orgId: 1
  folder: ''
  type: file
  disableDeletion: false
  updateIntervalSeconds: 10
    path: /etc/grafana/provisioning/dashboards

The other files are not as generic, because they depend on the type of datasource and your dashboards, so I won’t post them here.

Once you build the image and start a new grafana-container from it, the datasource- and dashboard-definitions will automatically be loaded. More details can be found in the Grafana documentation under Provisioning.

See also