Install Grafana Loki on VPS — Log Aggregation System
Grafana Loki is a log aggregation system designed to work alongside Grafana — collecting logs from all services in one place, enabling real-time log viewing via Grafana, searching with LogQL, and setting up alerts when error patterns occur. Unlike the ELK Stack (Elasticsearch) which indexes every field and consumes significant disk space, Loki indexes only labels, reducing disk usage by more than 10 times and offering simpler setup. This guide covers installing Loki + Promtail + Grafana using Docker Compose, collecting logs from Nginx, Docker containers, and systemd services.
Loki Stack Architecture
- Loki: The core log storage and retrieval system — comparable to Elasticsearch but far more lightweight
- Promtail: An agent running on every server that ships logs to Loki (similar to Logstash or Filebeat)
- Grafana: A dashboard for querying and visualizing logs using LogQL
- LogQL: Loki's query language, similar to PromQL — filter by labels and regex patterns
Installation with Docker Compose
mkdir -p /opt/loki/{config,data} && cd /opt/loki
# Create Loki configuration
cat > config/loki-config.yml << 'EOF'
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2020-10-24
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
ruler:
alertmanager_url: http://localhost:9093
limits_config:
retention_period: 720h # Keep logs for 30 days
EOF
# Create Promtail configuration
cat > config/promtail-config.yml << 'EOF'
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: system
static_configs:
- targets: [localhost]
labels:
job: varlogs
host: my-vps
__path__: /var/log/*.log
- job_name: nginx
static_configs:
- targets: [localhost]
labels:
job: nginx
host: my-vps
__path__: /var/log/nginx/*.log
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
refresh_interval: 5s
relabel_configs:
- source_labels: [__meta_docker_container_name]
regex: '/(.*)'
target_label: container
EOF
# Create docker-compose.yml
cat > docker-compose.yml << 'EOF'
version: "3.9"
services:
loki:
image: grafana/loki:latest
restart: unless-stopped
ports:
- "127.0.0.1:3100:3100"
volumes:
- ./config/loki-config.yml:/etc/loki/local-config.yaml
- ./data:/loki
command: -config.file=/etc/loki/local-config.yaml
promtail:
image: grafana/promtail:latest
restart: unless-stopped
volumes:
- ./config/promtail-config.yml:/etc/promtail/config.yml
- /var/log:/var/log:ro
- /var/run/docker.sock:/var/run/docker.sock
command: -config.file=/etc/promtail/config.yml
depends_on:
- loki
grafana:
image: grafana/grafana:latest
restart: unless-stopped
ports:
- "127.0.0.1:3000:3000"
environment:
GF_SECURITY_ADMIN_PASSWORD: CHANGE_ME_GRAFANA_PASS
GF_USERS_ALLOW_SIGN_UP: "false"
volumes:
- grafana_data:/var/lib/grafana
depends_on:
- loki
volumes:
grafana_data:
EOF
docker-compose up -d
Setting Up Nginx Reverse Proxy for Grafana
nano /etc/nginx/sites-available/grafana
server {
listen 80;
server_name logs.yourdomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name logs.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/logs.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/logs.yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1: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;
}
}
ln -s /etc/nginx/sites-available/grafana /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx
certbot --nginx -d logs.yourdomain.com
Adding Loki Data Source in Grafana
# Open Grafana at https://logs.yourdomain.com
# Login: admin / password you set
# Add Data Source:
# Home → Connections → Data sources → Add data source → Loki
# URL: http://loki:3100
# Save & Test → should show "Data source connected and labels found"
# Open Explore → select Loki → enter a query:
# {job="nginx"} |= "ERROR" # Nginx logs containing ERROR
# {job="varlogs"} |= "fail" # System logs containing fail
# {container="myapp"} | json # Docker container logs parsed as JSON
Basic LogQL Queries
# Filter by label
{job="nginx"}
# Filter text in log line
{job="nginx"} |= "404"
{job="nginx"} != "healthcheck" # Exclude healthcheck logs
# Regex filter
{job="nginx"} |~ "5[0-9]{2}" # HTTP 5xx errors
# Parse JSON logs
{job="myapp"} | json | level="error"
# Rate of errors over 5 minutes (for metrics)
rate({job="nginx"} |= "error" [5m])
# Top 10 most frequent IP addresses
topk(10, sum by (remote_addr) (
count_over_time({job="nginx"}[1h])
))
Setting Up Alerts for High Error Rates
# In Grafana: Alerting → Alert rules → New alert rule
# Data source: Loki
# Query:
# sum(rate({job="nginx"} |= "error" [5m])) > 10
# Set up Contact Point: Alerting → Contact points → Add
# Supports Email, Slack, PagerDuty, Telegram, Line
# Set up Notification Policy: Alerting → Notification policies
# Define which alerts route to which contact points
drop_rate_limited_batches: true in the Promtail config and use pipeline stages to filter unwanted logs before sending — this significantly reduces network traffic and storage usage.Verify Loki Stack is Working Correctly
# Check all containers
docker-compose ps
# Check Loki API
curl -s http://localhost:3100/ready
# Should return "ready"
# View labels received by Loki
curl -s http://localhost:3100/loki/api/v1/labels | python3 -m json.tool
# View latest logs from nginx job
curl -s -G http://localhost:3100/loki/api/v1/query_range \
--data-urlencode 'query={job="nginx"}' \
--data-urlencode 'limit=5' \
--data-urlencode "start=$(date -d '5 minutes ago' +%s)000000000" \
--data-urlencode "end=$(date +%s)000000000" \
| python3 -m json.tool | head -30
# Check Promtail logs
docker-compose logs promtail --tail=20
Common Issues & Troubleshooting
Error: "entry out of order" in Loki logs
Promtail is sending logs with non-sequential timestamps — common when a log file is written to by multiple processes simultaneously.
# Add to loki-config.yml in the limits_config section
limits_config:
reject_old_samples: false
reject_old_samples_max_age: 168h # Accept logs up to 7 days old
# Or in ingester config:
# max_chunk_age: 2h
Promtail Not Sending Logs from Docker Containers
The Docker socket requires read permissions and the container's logging driver must be json-file.
# Check the Docker logging driver for a container
docker inspect CONTAINER_NAME | grep -A5 LogConfig
# Must show:
# "Type": "json-file"
# If using a different driver, change it in the app's docker-compose
services:
myapp:
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
Loki Disk Usage Growing Continuously
Set a retention policy to automatically delete old logs.
# Add to loki-config.yml
compactor:
working_directory: /loki/compactor
compaction_interval: 10m
retention_enabled: true
retention_delete_delay: 2h
retention_delete_worker_count: 150
limits_config:
retention_period: 720h # 30 days
# Restart Loki after config changes
docker-compose restart loki
Grafana Shows "No data" Despite Loki Receiving Logs
Usually caused by time range in Explore not matching the actual log timestamps.
# Check log timestamps directly in Loki
curl -s "http://localhost:3100/loki/api/v1/query?query={job=\"nginx\"}&limit=1" \
| python3 -c "import sys,json; d=json.load(sys.stdin); print(d['data']['result'][:1])"
# If timezone is mismatched, fix in Grafana:
# Admin → Preferences → Timezone → Server Time
Frequently Asked Questions
How is Loki different from ELK Stack (Elasticsearch)?
Loki indexes only labels, not log content, making it far more disk and memory-efficient than ELK. However, it's slower for full-text searches since it must scan log content. Elasticsearch is faster for complex queries and aggregations but requires significantly more resources (8+ GB RAM for production use). Loki is ideal for VPS with limited RAM where you primarily need tail-log viewing and alerting rather than deep analytics.
Does Promtail Support Windows Event Logs?
Grafana Agent (the newer replacement for Promtail) supports Windows Event Log via the windows_events scrape config. Older Promtail versions only support Linux, but if an application writes logs to files on Windows, Promtail can still ship them normally.
How Long Can I Store Logs on a VPS?
It depends on disk space and log volume — Loki compresses logs very efficiently. A typical server generating 100 MB of logs per day can store 6 months of logs on a 20 GB disk. Set the retention policy to match your available disk space and you won't need additional storage.