Guide: implement journald retention and compression policies on Ubuntu servers (VPS) — step by step

By · Published on · 8 min read

Closed notebook on a wooden railing with a tiny camera and a pen; blurred background
Closed notebook with a tiny camera and pen, green blurred background. Photo: Jason Morrison / Pexels

A practical guide to implementing retention and compression policies for systemd-journald on Ubuntu servers (VPS). You’ll learn how to limit logs by size and age, enable compression, control bursty logging and apply changes safely. At the end you’ll know how to verify the impact and monitor disk usage while keeping local traceability for support and audits without wasting space.

When to adjust journald policies

On VPSs, disk space is finite. Log spikes can fill the root partition and degrade services. journald rotates logs by default, but generic defaults rarely match your risk profile and budget.

Signs it’s time to tune: accelerating growth, low‑disk alerts and difficulty investigating older incidents.

If you centralize logs, keep a small local window for quick diagnostics. For long retention and full‑text search, use a dedicated pipeline like in the Fluentd + Elasticsearch guide for PHP logs on a VPS.

The goal is to limit size and age, preserve headroom on the filesystem and enable compression with a predictable CPU impact.

  • Disk‑full alerts after verbose deployments
  • Services accidentally running at debug level
  • Audits requiring a minimum local window
  • Apps that only write to journald, without logrotate

Prerequisites and initial checks

You need root access, systemd active and a supported Ubuntu release. Before changing anything, discover the systemd version, current disk usage and whether storage is persistent.

Save a snapshot of the current state so you can compare after applying the policy. Vacuum operations remove historic logs — perform them consciously.

# Versão do systemd e recursos
systemd --version

# Uso atual de disco pelos journals
journalctl --disk-usage

# Espaço livre na partição raiz
df -h /

# Verifica se o armazenamento é persistente (/var/log/journal)
[ -d /var/log/journal ] && echo "persistente" || echo "volátil"

# Quem é mais verboso (amostra)
journalctl -n 200 --priority=info --no-pager | awk '{print $5}' | sort | uniq -c | sort -nr | head

How journald stores, rotates and compresses

journald uses binary files and rotates them automatically. Policies combine three axes: total space limit, file size/count limits and maximum entry age.

Compression reduces space for large entries with a moderate CPU cost on write and read. Choose limits that leave safe headroom on disk.

Option What it controls When to use
Storage Where logs are stored: persistent (/var/log/journal) or volatile Use persistent to keep logs across reboots
SystemMaxUse Total cap for /var/log/journal Predict usage and fit small disks
SystemKeepFree Minimum free space to keep on the root filesystem Avoid consuming the system's reserved space
SystemMaxFileSize Maximum size per journal file Smaller files and more frequent rotations
SystemMaxFiles Maximum number of files Limit fragmentation and history by count
RuntimeMaxUse Cap for /run/log/journal (volatile) Control usage during boot and on volatile storage
RuntimeKeepFree Minimum free space for /run Avoid pressure on tmpfs during peaks
Compress Compress large entries Reduces space and I/O when CPU allows
Seal Sign files for integrity Use in environments with integrity requirements
RateLimitIntervalSec / RateLimitBurst Tolerance for repeated bursts Reduce noise and I/O from repeated messages
MaxRetentionSec Maximum age of retained history Set a fixed time window when supported

Practical profiles for VPS (starter examples)

Tune values to your disk size and environment criticality. Use these starting points and test under your workload. All assume persistent storage and compression enabled.

If you centralize logs, keep a smaller local window and rely on the aggregator for search. For metrics and correlation, see Structured JSON logs and request correlation.

  • Economy: SystemMaxUse=300M, SystemKeepFree=200M, SystemMaxFileSize=50M, SystemMaxFiles=20, RuntimeMaxUse=100M, MaxRetentionSec=7d
  • Balanced: SystemMaxUse=1G, SystemKeepFree=500M, SystemMaxFileSize=100M, SystemMaxFiles=50, RuntimeMaxUse=200M, MaxRetentionSec=30d
  • Audit-friendly: SystemMaxUse=2G, SystemKeepFree=1G, SystemMaxFileSize=200M, SystemMaxFiles=80, RuntimeMaxUse=400M, MaxRetentionSec=60d

Configure a drop-in at /etc/systemd/journald.conf.d

Use a drop-in so the packaged default file stays intact and audits are easier. The example below is a balanced profile — adjust sizes and windows to your context.

After saving, restart the service to apply. This guide covers how to implement journald retention and compression policies on Ubuntu VPS without unexpected space issues.

sudo mkdir -p /etc/systemd/journald.conf.d
sudo tee /etc/systemd/journald.conf.d/10-retencao-compressao.conf > /dev/null <<'EOF'
[Journal]
# Armazenamento persistente
Storage=persistent

# Limites em /var/log/journal
SystemMaxUse=1G
SystemKeepFree=500M
SystemMaxFileSize=100M
SystemMaxFiles=50

# Limites em /run/log/journal (volátil)
RuntimeMaxUse=200M
RuntimeKeepFree=50M

# Compressão e integridade
Compress=yes
Seal=yes

# Rajadas de mensagens repetidas
RateLimitIntervalSec=30s
RateLimitBurst=1000

# Janela máxima por tempo (se suportado na sua versão)
MaxRetentionSec=30d
EOF

# Aplica a nova configuração
sudo systemctl restart systemd-journald.service

Apply now, rotate and reclaim space

The new policy governs future rotations. To free space immediately, force a rotation and run vacuum. Vacuum deletes old files — confirm required history was collected externally if needed.

Start conservative. Validate and only then shrink the window or lower caps further.

# Uso atual
journalctl --disk-usage

# Força rotação imediata
yes | sudo journalctl --rotate

# Limpa por tamanho/tempo/quantidade (ajuste conforme sua política)
sudo journalctl --vacuum-size=1G
sudo journalctl --vacuum-time=30d
sudo journalctl --vacuum-files=50

# Confere novamente
journalctl --disk-usage

Verification and continuous monitoring

Confirm journald read the drop‑in and that space usage aligns with targets. Periodically monitor minimum free space and journal usage.

For capacity metrics and alerts, build a dashboard. See the practical guide: set up Prometheus & Grafana with Docker Compose on a VPS.

As part of hardening and safe operations, review policies alongside the VPS Linux security checklist. For observability stack comparisons, see the Prometheus+Grafana vs Loki+Tempo comparison.

  • Check the effective merged configuration
  • Ensure persistent storage and correct permissions
  • Monitor minimum free space and total journal usage
# Configuração efetiva (inclui drop-ins)
systemd-analyze cat-config systemd/journald.conf

# Diretório persistente e arquivos presentes
test -d /var/log/journal && ls -lh /var/log/journal/*/*.journal || echo "armazenamento volátil"

# Uso total e por arquivo
journalctl --disk-usage
sudo du -h /var/log/journal/* --max-depth=1 2>/dev/null | sort -h

Common troubleshooting

Common issues include unexpected volatile storage, incorrect permissions, unknown keys on older versions and corruption after crashes.

If an application produces too many logs, reduce the verbosity in the service itself. journald policies mitigate global impact, but the root cause should be fixed at source.

When needed, reapply the policy and run vacuum carefully. This guide to implementing journald retention and compression policies on Ubuntu VPS helps avoid surprises.

  • journald uses volatile storage: create /var/log/journal with proper permissions
  • Unknown key (e.g. MaxRetentionSec): remove the option or upgrade the OS
  • Files corrupted after power loss: check integrity and vacuum
  • Overly aggressive cleanup: increase SystemKeepFree or SystemMaxUse
# 1) Garantir armazenamento persistente
sudo mkdir -p /var/log/journal
sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo chown root:systemd-journal /var/log/journal
sudo chmod 2755 /var/log/journal
sudo systemctl restart systemd-journald

# 2) Conferir mensagens sobre chaves desconhecidas
journalctl -u systemd-journald -b | grep -i "unknown" || true

# 3) Verificar integridade e limpar excedentes
sudo journalctl --verify || true
yes | sudo journalctl --vacuum-size=1G --vacuum-time=30d

Frequently asked questions

Does journald compression use a lot of CPU?

Generally the cost is moderate on writes and reads. It usually pays off by reducing I/O and disk usage. On CPU‑constrained VPSs, enable it during lower load windows and monitor the impact before rolling it out globally.

Is it better to limit by size or by time?

Both are useful and can coexist. On small disks, a size cap gives predictability. If you must guarantee a minimum time window, combine size with time. Older systemd versions without MaxRetentionSec require using space limits and vacuum by time.

Does journald replace rsyslog?

For many servers, journald covers collection, rotation and local queries. If you need legacy protocols or specific integrations, keep rsyslog or a dedicated agent alongside journald.

How do I contain a service that logs too much?

Lower the application's log level or adjust the corresponding systemd unit. journald rate‑limit policies reduce repeated bursts, but the real fix is to correct verbosity at the service.

Can I delete logs manually?

Prefer journalctl vacuum commands to maintain consistency. Deleting files directly can cause inconsistencies. If you must manipulate files, stop journald first and restart it afterward. Consider audit implications.

Need a review of your VPS log policy?

Describe your setup, disk limits and required retention windows. We’ll discuss safe journald retention and compression options that balance auditability and capacity.

Talk about my scenario

See also