For our Blog Visitor only Get Additional 3 Month Free + 10% OFF on TriAnnual Plan YSBLOG10
Grab the Deal

How to Optimize ClamAV on Linux Server – Complete Guide

To optimize ClamAV on a Linux server, run the daemon (clamd) instead of clamscan, keep signatures up to date with freshclam, tune threads and scan limits, exclude noisy paths, schedule smart scans (on-access plus daily incrementals), cache databases on fast storage, and monitor logs to balance speed, accuracy, and CPU/RAM usage.

Why Optimizing ClamAV on Linux Server Matters

ClamAV is a reliable open-source antivirus engine for Linux, but default settings are conservative. If you want faster scans, fewer false positives, and lower CPU spikes, you need to optimize ClamAV on Linux server the right way. This guide covers practical tuning that we use on production servers to keep performance smooth without sacrificing security.

Quick Wins: 80/20 Checklist

  • Use clamd + clamdscan (not clamscan) for persistent, multi-threaded scanning.
  • Update signatures frequently with freshclam; consider a local mirror at scale.
  • Exclude ephemeral paths like /proc, /sys, /dev, and heavy cache directories you trust.
  • Tune MaxThreads, StreamMaxLength, and scan-size limits for your workload.
  • Put DatabaseDirectory and TemporaryDirectory on fast storage (SSD/tmpfs).
  • Use on-access scanning (clamonacc) for real-time protection, plus scheduled incrementals.
  • Monitor logs and clamd metrics; adjust when you see bottlenecks or false positives.

Understand Your Workload Before Tuning

Scan patterns vary by server role. A web hosting server sees many small uploads; a mail gateway processes streams; a file server stores large archives. Note your average file size, peak concurrency, and I/O limits. This determines thread counts, scan-size caps, and exclusion strategy. Optimization is context-driven, not one-size-fits-all.

Install and Keep ClamAV Updated

Install the engine, daemon, and updater using your distribution’s packages. Make sure your OS repositories are not stale so you get a recent ClamAV version.

# Debian/Ubuntu
sudo apt update
sudo apt install clamav clamav-daemon clamav-freshclam

# RHEL/CentOS/Alma/Rocky
sudo dnf install clamav clamd clamav-update

# openSUSE
sudo zypper install clamav clamav-daemon clamav-freshclam

Enable services and perform an initial database update.

sudo systemctl enable --now clamav-freshclam
sudo systemctl enable --now clamav-daemon   # may be named clamd@scan or clamd

# If the database is empty, you may need:
sudo freshclam

Switch to clamd + clamdscan (The Biggest Speedup)

clamscan loads signatures into memory every run. clamd keeps them warm in RAM and serves multiple scan requests simultaneously. Use clamdscan to talk to the daemon via socket or TCP for significant speed gains and lower CPU churn.

# /etc/clamav/clamd.conf (path may differ by distro)

# Socket (preferred) or TCP
LocalSocket /run/clamd.scan/clamd.sock
FixStaleSocket true

# Threads and queue - tune for your CPU and I/O
MaxThreads 8
MaxQueue 100

# Limits (protect your server from huge or deeply nested files)
MaxScanSize 750M
MaxFileSize 250M
MaxRecursion 30
MaxFiles 20000
StreamMaxLength 750M

# Performance
ConcurrentDatabaseReload yes
ReadTimeout 300
Bytecode yes
BytecodeSecurity TrustSigned
BytecodeTimeout 120000

# Exclusions (example; adapt to your environment)
ExcludePath ^/proc/
ExcludePath ^/sys/
ExcludePath ^/dev/
ExcludePath ^/run/
ExcludePath ^/var/log/
ExcludePath ^/var/cache/

# Logging
LogFile /var/log/clamav/clamd.log
LogTime yes

# Temporary and DB paths - put on fast storage when possible
TemporaryDirectory /tmp
DatabaseDirectory /var/lib/clamav

Set MaxThreads near (but not above) the number of CPU cores you can spare for scanning. Keep headroom for web, MySQL, PHP-FPM, and mail services. If you host busy sites, start with 4–8 threads, benchmark, then iterate.

Tune freshclam and Signature Management

freshclam pulls official databases (main, daily, bytecode). Update frequency should be responsible: too low risks exposure; too high risks throttling. Six to twelve checks per day suits most servers; mail gateways may go higher.

# /etc/clamav/freshclam.conf

DatabaseMirror database.clamav.net
Checks 8
DNSDatabaseInfo current.cvd.clamav.net

# Networking
ConnectTimeout 30
ReceiveTimeout 30

# Logging
UpdateLogFile /var/log/clamav/freshclam.log
LogTime yes

# If you run a private mirror for multiple servers:
# PrivateMirror your-mirror.example.com
# ScriptedUpdates yes

If you manage dozens of servers, host a local mirror and point all nodes to it. This reduces bandwidth, speeds updates, and avoids public mirror rate limits.

Exclude Noisy and Safe Paths

Scanning pseudo-filesystems or high-churn caches wastes CPU. Exclude paths that cannot contain real malware or that you already trust. Keep uploads, mail spools, and web roots in scope.

  • Safe to exclude: /proc, /sys, /dev, /run, package caches, system logs.
  • Optional: backup mounts that are immutable or already scanned on a staging node.
  • Be careful with: /tmp, /var/tmp, /home, /var/www, /var/mail — usually keep these included.

Use ExcludePath in clamd.conf or –exclude/–exclude-dir with clamscan/clamdscan to minimize noise and speed up jobs.

Smart Scheduling: Real-Time, Incremental, and Full Scans

Combine on-access scanning for instant protection with lightweight scheduled scans. This prevents malware from persisting while keeping routine load predictable.

Enable on-access scanning (fanotify)

# Start clamonacc with clamd. Adjust paths to watch.
sudo clamonacc --fdpass \
  --log=/var/log/clamav/onaccess.log \
  --include-path=/var/www \
  --include-path=/var/mail \
  --exclude-path=/proc --exclude-path=/sys --exclude-path=/dev

On-access scanning requires a modern kernel (fanotify). Run it as root or a user with enough privileges. Start it via systemd or a supervisor for persistence.

Schedule daily/weekly scans

# Daily quick incremental scan (changes in last 24h)
0 2 * * * root find /var/www -type f -mtime -1 -print0 | \
  xargs -0 -r clamdscan --fdpass --multiscan --log=/var/log/clamav/daily-www.log

# Weekly full scan off-peak
30 3 * * 0 root clamdscan --fdpass --multiscan --log=/var/log/clamav/full.log /

Use –multiscan to parallelize across threads. Prefer clamdscan over clamscan for speed. Run full scans during low traffic windows.

Resource Tuning: CPU, I/O, Memory

  • Threads: Start with MaxThreads = 50–75% of available cores. Measure and adjust.
  • Scan limits: Cap MaxScanSize and StreamMaxLength to prevent giant archives from blocking threads.
  • TemporaryDirectory: Point to a fast disk or tmpfs, but ensure enough free space.
  • DatabaseDirectory: Keep on SSD. Faster signature reads improve startup and reloads.
  • I/O scheduling: If scans compete with databases, consider ionice/CPU shares for clamd.
# Example: start clamd with lower I/O priority
sudo ionice -c2 -n6 systemctl start clamav-daemon

Watch memory usage during full scans. If the kernel starts swapping, lower MaxThreads or move TemporaryDirectory off tmpfs to disk with more space.

Practical clamscan/clamdscan Command Examples

# Scan uploads directory and show only infected files
clamdscan --fdpass --multiscan --infected /var/www/html/wp-content/uploads

# Exclude specific patterns
clamdscan --fdpass --multiscan \
  --exclude-dir='^/var/www/cache/' \
  --exclude='\.log$' \
  /var/www

# Quarantine strategy (move, don't delete)
INFECTED=/quarantine
mkdir -p "$INFECTED"
clamscan -r --move="$INFECTED" --infected /home

In production, prefer moving infected files to a quarantine folder rather than deleting them. This preserves evidence and reduces false-positive risk.

Logging, Monitoring, and Alerting

  • Centralize logs: clamd.log, freshclam.log, onaccess.log.
  • Alerting: Forward “FOUND” events to your SIEM, email, or chat via rsyslog or a small wrapper script.
  • Metrics: Use clamdtop to monitor queue, threads, and throughput in real time.
# Quick alert on detection (example)
tail -Fn0 /var/log/clamav/clamd.log | \
  awk '/FOUND/ {system("mail -s \"ClamAV detection\" admin@example.com <<< \""$0"\"")}'

Reduce False Positives and Handle Overrides

  • Be careful with PUA (Potentially Unwanted Applications). Enable only if you need aggressive detections.
  • Use ExcludePath for trusted software caches and build artifacts.
  • For a one-off false positive, create an ignore entry using local.ign2 in DatabaseDirectory.
# Example ignore file (one signature per line)
# /var/lib/clamav/local.ign2
Win.Trojan.Example:abcdef1234567890abcdef1234567890

Only ignore after verifying with multiple scanners and hashes. Document every override for audits.

Common Mistakes to Avoid

  • Running clamscan for routine jobs (too slow) instead of clamdscan.
  • Scanning /proc, /sys, or large backup mounts unnecessarily.
  • Enabling excessive Checks in freshclam leading to throttling.
  • Deleting infected files automatically without quarantine.
  • Ignoring logs and assuming defaults are “set and forget.”

Optimization Examples by Server Role

Web hosting servers

  • On-access for uploads and web roots.
  • Daily incremental scans of /var/www and user homes.
  • Exclude caches (image caches, compiled templates).
  • Threads: 4–8 depending on PHP-FPM/DB load.

Mail gateways

  • High Checks for freshclam (e.g., 12–24), but respect mirror policies.
  • Stream scanning via clamd with MTA integration.
  • Tight StreamMaxLength and MaxFileSize to keep throughput high.

File servers

  • On-access scanning on shared mounts.
  • Weekly full scan off-peak with quarantine.
  • Consider excluding huge immutable archives, but scan them during maintenance windows.

Troubleshooting Performance

  • High CPU all day: Reduce MaxThreads or lower on-access scope.
  • Slow web responses during scans: Lower ionice priority or schedule scans off-peak.
  • Scan aborts on big files: Increase MaxScanSize/StreamMaxLength and ensure TemporaryDirectory has space.
  • Freshclam errors: Check firewall/DNS, adjust Checks, or use a nearby mirror.

Security and Compliance Notes

  • Quarantine retention and chain of custody for incident response.
  • Access controls on logs and quarantine directories.
  • Periodic verification of signature freshness and daemon uptime with systemd health checks.
# Simple systemd health probe (service override snippet)
# /etc/systemd/system/clamav-daemon.service.d/override.conf
[Service]
ExecStartPost=/bin/sh -c 'sleep 5 && /usr/bin/clamdscan --version || systemctl restart clamav-daemon'

Need Managed Hardening? YouStable Can Help

If you prefer experts to configure and maintain ClamAV, YouStable’s managed Linux hosting includes security hardening, on-access scanning, tuned clamd profiles, and proactive monitoring. We optimize for your workload (WordPress, mail, file shares) and keep performance steady while meeting security best practices.

FAQs: Optimizing ClamAV on Linux Server

Is clamd faster than clamscan?

Yes. clamd loads signatures into memory once and serves multiple requests concurrently. clamscan re-reads databases each run, which is slower and CPU-heavy. For production, use clamd + clamdscan for significant performance gains.

How often should I run freshclam?

For most servers, 6–12 checks per day balances freshness and mirror fairness. Mail gateways or high-risk environments may increase this. If you manage many servers, create a local mirror and point freshclam to it to avoid throttling.

What directories should I exclude from ClamAV scans?

Exclude pseudo-filesystems (/proc, /sys, /dev, /run), system logs, and trusted caches. Keep user data, uploads, web roots, mail spools, and temp directories in scope. Exclusions should be justified and documented.

How do I reduce false positives safely?

Verify with multiple scanners and hashes. Prefer ExcludePath for known-safe locations. For specific signatures, add a line to local.ign2 to ignore that signature. Avoid broad ignores that hide future threats.

Should I enable on-access scanning on all paths?

No. Start with high-risk paths (uploads, user homes, mail). Broad on-access hooks can increase overhead. Combine targeted on-access with scheduled incrementals and a weekly full scan to balance protection and performance.

Prahlad Prajapati

Prahlad is a web hosting specialist and SEO-focused organic growth expert from India. Active in the digital space since 2019, he helps people grow their websites through clean, sustainable strategies. Passionate about learning and adapting fast, he believes small details create big success. Discover his insights on web hosting and SEO to elevate your online presence.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top