Install and Use Grafana on Ubuntu: Complete Guide

Master Grafana setup for monitoring & visualization

Page content

Grafana is the leading open-source platform for monitoring and observability, transforming metrics, logs, and traces into actionable insights through stunning visualizations.

grafana This is a screenshot from the Grafana website.

What is Grafana?

Grafana is a multi-platform open-source analytics and interactive visualization web application. It provides charts, graphs, and alerts for the web when connected to supported data sources. Grafana is widely used in DevOps for monitoring infrastructure, applications, and services.

Key Features:

  • Universal Dashboard Create beautiful, dynamic dashboards with flexible templating
  • Multiple Data Sources Connect to 150+ data sources including Prometheus, InfluxDB, Elasticsearch, MySQL, PostgreSQL, and more
  • Alerting Unified alerting system with notification channels (Slack, PagerDuty, email, webhooks)
  • Team Collaboration Share dashboards, create teams, and manage user permissions
  • Plugin Ecosystem Extend functionality with panels, data sources, and apps
  • Cloud Native Perfect for Kubernetes, Docker, and cloud environments

Why Grafana on Ubuntu?

Ubuntu LTS versions provide a stable, secure foundation for hosting Grafana. If you’re starting fresh or need to set up a new Ubuntu environment for your monitoring infrastructure, check out our comprehensive guide on how to install Ubuntu 24.04 with useful tools to get your system ready.

Benefits include:

  • Long-term support and security updates
  • Large community and extensive documentation
  • Native APT repository support from Grafana Labs
  • Excellent Docker compatibility
  • Perfect for both development and production environments

Installation Methods

This is the most straightforward method, providing automatic updates through Ubuntu’s package manager. If you’re new to working with the Ubuntu terminal or want to boost your productivity, our Ubuntu keyboard shortcuts cheatsheet can help you navigate the system more efficiently.

Step 1: Install Prerequisites

sudo apt-get install -y apt-transport-https software-properties-common wget

Step 2: Add Grafana GPG Key

sudo mkdir -p /etc/apt/keyrings/
wget -q -O - https://apt.grafana.com/gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/grafana.gpg > /dev/null

Step 3: Add Grafana APT Repository

For stable releases:

echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list

Step 4: Update and Install Grafana

sudo apt-get update
sudo apt-get install grafana

Step 5: Start and Enable Grafana Service

sudo systemctl daemon-reload
sudo systemctl start grafana-server
sudo systemctl enable grafana-server.service

Step 6: Verify Installation

sudo systemctl status grafana-server

Grafana will now be running on http://localhost:3000

Method 2: Install Using Docker

Docker provides isolation and easier management for containerized deployments.

Step 1: Install Docker (if not already installed)

sudo apt-get update
sudo apt-get install docker.io
sudo systemctl start docker
sudo systemctl enable docker

Step 2: Run Grafana Container

docker run -d \
  --name=grafana \
  -p 3000:3000 \
  -v grafana-storage:/var/lib/grafana \
  grafana/grafana-oss

For Persistence with Configuration:

docker run -d \
  --name=grafana \
  -p 3000:3000 \
  -v grafana-storage:/var/lib/grafana \
  -v $(pwd)/grafana.ini:/etc/grafana/grafana.ini \
  -e "GF_SERVER_ROOT_URL=http://your-domain.com" \
  -e "GF_SECURITY_ADMIN_PASSWORD=your-secure-password" \
  grafana/grafana-oss

Method 3: Install Using Docker Compose

Create a docker-compose.yml file:

version: '3.8'

services:
  grafana:
    image: grafana/grafana-oss:latest
    container_name: grafana
    restart: unless-stopped
    ports:
      - '3000:3000'
    volumes:
      - grafana-storage:/var/lib/grafana
      - ./grafana/provisioning:/etc/grafana/provisioning
    environment:
      - GF_SECURITY_ADMIN_USER=admin
      - GF_SECURITY_ADMIN_PASSWORD=your-secure-password
      - GF_USERS_ALLOW_SIGN_UP=false
      - GF_SERVER_ROOT_URL=http://your-domain.com

volumes:
  grafana-storage:

Start with:

docker-compose up -d

Initial Configuration

First Login

  1. Navigate to http://your-server-ip:3000
  2. Default credentials:
    • Username: admin
    • Password: admin
  3. You’ll be prompted to change the password immediately (highly recommended!)

Configure Your First Data Source

Example: Adding Prometheus

  1. Click Configuration (gear icon) → Data Sources
  2. Click Add data source
  3. Select Prometheus
  4. Configure:
    • Name: Prometheus
    • URL: http://localhost:9090 (adjust for your Prometheus instance)
    • Access: Server (default)
  5. Click Save & Test

Example: Adding InfluxDB

  1. Select InfluxDB as data source
  2. Configure:
    • Query Language: Flux or InfluxQL
    • URL: http://localhost:8086
    • Database: your_database_name
    • User/Password: your credentials
  3. Click Save & Test

Creating Your First Dashboard

  1. Click Create (+ icon) → Dashboard
  2. Click Add new panel
  3. Select your data source
  4. Write your query (example for Prometheus):
rate(http_requests_total[5m])
  1. Customize visualization:
    • Choose panel type (Graph, Gauge, Stat, Table, etc.)
    • Configure legends, axes, thresholds
    • Add transformations if needed
  2. Click Apply to save the panel
  3. Click Save dashboard (disk icon)

Advanced Configuration

Configure Grafana Settings

Edit the main configuration file:

sudo nano /etc/grafana/grafana.ini

Important Settings:

[server]
# Protocol (http, https, h2, socket)
protocol = http
http_port = 3000
domain = your-domain.com
root_url = http://your-domain.com

[security]
admin_user = admin
admin_password = your-secure-password
secret_key = your-secret-key

[users]
# Disable user signup
allow_sign_up = false
allow_org_create = false

[auth.anonymous]
enabled = false

[smtp]
enabled = true
host = smtp.gmail.com:587
user = your-email@gmail.com
password = your-app-password
from_address = your-email@gmail.com
from_name = Grafana

Restart after changes:

sudo systemctl restart grafana-server

Setting Up Reverse Proxy (Nginx)

Install Nginx:

sudo apt install nginx

Create Nginx Configuration:

sudo nano /etc/nginx/sites-available/grafana
server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Enable and restart:

sudo ln -s /etc/nginx/sites-available/grafana /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Enable HTTPS with Let’s Encrypt

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

Configure Alerting

Step 1: Configure Notification Channel

  1. Navigate to AlertingContact points
  2. Click New contact point
  3. Choose type (Email, Slack, PagerDuty, Webhook, etc.)
  4. Configure settings (e.g., Slack webhook URL)
  5. Test and save

Step 2: Create Alert Rule

  1. Edit a panel in your dashboard
  2. Click Alert tab
  3. Configure conditions:
    • When: avg()
    • Of: query(A, 5m, now)
    • Is Above: 80
  4. Set evaluation interval
  5. Add notification channel
  6. Save

Infrastructure Monitoring

Stack: Prometheus + Node Exporter + Grafana

Monitor system metrics:

  • CPU, memory, disk usage
  • Network traffic
  • System load
  • Disk I/O

For NVIDIA GPU monitoring specifically, you might want to explore specialized GPU monitoring applications for Linux/Ubuntu that integrate well with Grafana.

Import dashboard ID: 1860 (Node Exporter Full)

Kubernetes Monitoring

Stack: Prometheus + kube-state-metrics + Grafana

Monitor K8s cluster:

  • Pod and container metrics
  • Cluster resource usage
  • Deployment status
  • Ingress/service monitoring

Import dashboard ID: 15757 (Kubernetes Cluster Monitoring)

Application Performance Monitoring

Stack: Loki + Promtail + Grafana

Monitor application logs and metrics:

  • Request rates and latencies
  • Error rates
  • Log aggregation and filtering
  • Distributed tracing

Database Monitoring

Monitor MySQL, PostgreSQL, MongoDB:

  • Query performance
  • Connection pools
  • Slow queries
  • Replication status

Dashboard Best Practices

  1. Organize by Purpose: Create separate dashboards for different teams/services
  2. Use Variables: Create dynamic dashboards with template variables
  3. Set Appropriate Time Ranges: Default to meaningful time windows
  4. Add Annotations: Mark deployments and incidents
  5. Use Folders: Organize dashboards logically
  6. Enable Versioning: Track dashboard changes
  7. Set Refresh Intervals: Balance real-time needs with performance
  8. Add Documentation: Use text panels to explain metrics

Troubleshooting Common Issues

Grafana Service Won’t Start

# Check logs
sudo journalctl -u grafana-server -f

# Check configuration
sudo grafana-cli admin reset-admin-password newpassword

Data Source Connection Issues

  • Verify network connectivity: telnet datasource-host port
  • Check firewall rules
  • Verify credentials
  • Check data source service logs

Performance Issues

  • Reduce query time ranges
  • Optimize data source queries
  • Increase server resources
  • Use caching where possible
  • Consider query result caching

Dashboard Not Loading

  • Clear browser cache
  • Check browser console for errors
  • Verify dashboard JSON isn’t corrupted
  • Check Grafana server logs

Backup and Maintenance

Backup Grafana Database

# Stop Grafana
sudo systemctl stop grafana-server

# Backup SQLite database
sudo cp /var/lib/grafana/grafana.db /backup/grafana-$(date +%Y%m%d).db

# Backup configuration
sudo cp /etc/grafana/grafana.ini /backup/grafana-ini-$(date +%Y%m%d).bak

# Start Grafana
sudo systemctl start grafana-server

Automated Backup Script

Here’s a bash script to automate your Grafana backups. If you need a quick reference for bash scripting syntax and commands, check out our Bash cheat sheet for helpful tips and examples.

#!/bin/bash
BACKUP_DIR="/backup/grafana"
mkdir -p $BACKUP_DIR
DATE=$(date +%Y%m%d_%H%M%S)

# Backup database
sudo cp /var/lib/grafana/grafana.db $BACKUP_DIR/grafana-$DATE.db

# Backup dashboards via API
curl -H "Authorization: Bearer YOUR_API_KEY" \
  http://localhost:3000/api/search?type=dash-db | \
  jq -r '.[] | .uid' | \
  xargs -I{} curl -H "Authorization: Bearer YOUR_API_KEY" \
  http://localhost:3000/api/dashboards/uid/{} > $BACKUP_DIR/dashboards-$DATE.json

# Keep only last 30 days
find $BACKUP_DIR -mtime +30 -delete

Update Grafana

# APT method
sudo apt update
sudo apt upgrade grafana

# Docker method
docker pull grafana/grafana-oss:latest
docker-compose down
docker-compose up -d

Security Hardening

  1. Change Default Credentials immediately
  2. Use HTTPS with valid certificates
  3. Configure Firewall:
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    sudo ufw enable
    
  4. Disable Anonymous Access
  5. Use Strong Authentication (LDAP, OAuth, SAML)
  6. Regular Updates Keep Grafana updated
  7. Limit User Permissions Use role-based access control
  8. Enable Audit Logging
  9. Use Read-Only Data Sources where possible
  10. Implement Rate Limiting

Monitoring Grafana Itself

Monitor your Grafana instance:

  1. Enable metrics endpoint in grafana.ini:
    [metrics]
    enabled = true
    
  2. Add Grafana as Prometheus target
  3. Import Grafana metrics dashboard

Useful Plugins

Install plugins via CLI:

sudo grafana-cli plugins install <plugin-id>
sudo systemctl restart grafana-server

Recommended Plugins:

  • grafana-piechart-panel: Enhanced pie charts
  • grafana-worldmap-panel: Geographic data visualization
  • grafana-clock-panel: Display time and date
  • grafana-simple-json-datasource: Connect to custom JSON APIs
  • alexanderzobnin-zabbix-app: Zabbix integration

Integration Examples

Grafana + Prometheus + Node Exporter

Complete monitoring stack setup:

# Install Node Exporter
wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz
tar xvfz node_exporter-1.7.0.linux-amd64.tar.gz
sudo cp node_exporter-1.7.0.linux-amd64/node_exporter /usr/local/bin/
sudo useradd -rs /bin/false node_exporter

# Create systemd service
sudo tee /etc/systemd/system/node_exporter.service << EOF
[Unit]
Description=Node Exporter
After=network.target

[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl start node_exporter
sudo systemctl enable node_exporter

Grafana with InfluxDB and Telegraf

Time-series monitoring setup:

# Install InfluxDB
wget -q https://repos.influxdata.com/influxdata-archive_compat.key
echo '393e8779c89ac8d958f81f942f9ad7fb82a25e133faddaf92e15b16e6ac9ce4c influxdata-archive_compat.key' | sha256sum -c && cat influxdata-archive_compat.key | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/influxdata-archive_compat.gpg > /dev/null
echo 'deb [signed-by=/etc/apt/trusted.gpg.d/influxdata-archive_compat.gpg] https://repos.influxdata.com/debian stable main' | sudo tee /etc/apt/sources.list.d/influxdata.list
sudo apt update && sudo apt install influxdb
sudo systemctl start influxdb
sudo systemctl enable influxdb

# Install Telegraf
sudo apt install telegraf
sudo systemctl start telegraf
sudo systemctl enable telegraf

Performance Optimization

Query Optimization

  • Use appropriate time ranges
  • Limit data points returned
  • Use caching strategies
  • Aggregate data at source when possible
  • Use recording rules in Prometheus

Server Optimization

[database]
# Increase max connections
max_open_conn = 300
max_idle_conn = 100

[dataproxy]
# Timeout settings
timeout = 30
keep_alive_seconds = 30

[rendering]
# Enable concurrent render limit
concurrent_render_limit = 10

Conclusion

Grafana on Ubuntu provides a powerful, flexible platform for monitoring and observability. Whether you’re monitoring a single server or a massive Kubernetes cluster, Grafana’s rich visualization capabilities, extensive data source support, and active community make it an excellent choice for DevOps teams.

Start with a simple setup using the APT repository method, connect your first data source, and gradually expand your monitoring capabilities. Remember to prioritize security, regular backups, and performance optimization as your Grafana deployment grows.

With proper configuration and best practices, Grafana becomes an indispensable tool in your observability stack, providing actionable insights that help maintain reliable, performant systems.