Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Nagios Monitoring for Servers

By Kokil Thapa | Last reviewed: August 2026

Nagios monitoring for servers remains the industry-standard approach for teams needing transparent, self-hosted infrastructure observability without recurring SaaS fees. While modern observability platforms offer convenience, many Nepal-based businesses and global SMEs still require direct control over their monitoring stack due to budget constraints or data sovereignty requirements. This guide covers the practical reality of deploying and maintaining Nagios Core on Ubuntu 24.04 LTS in 2026, focusing on configuration patterns that actually survive production use.

How do you install Nagios Core on Ubuntu 24.04 for server monitoring?

Installing Nagios Core from source on Ubuntu 24.04 LTS provides the latest stable release (4.5.x series) and avoids outdated repository packages. Before starting, ensure your server has at least 2GB RAM and PHP 8.2+ installed, as the web interface depends on it. For teams managing server security in Nepal, always run Nagios on a dedicated management host isolated from public-facing application servers.

Prerequisites and dependency installation

Nagios Core compiles against Apache, PHP, and several development libraries. Install all build dependencies in one command to avoid mid-build failures:

sudo apt update && sudo apt upgrade -y
sudo apt install -y apache2 php8.2 libapache2-mod-php8.2 \
    php8.2-gd php8.2-mysql php8.2-xml php8.2-mbstring \
    build-essential libgd-dev openssl libssl-dev \
    unzip wget curl autoconf automake pkg-config

Create the nagios user and group before compiling. The web interface also requires membership in the nagcmd group for external command execution:

sudo useradd -m -s /bin/bash nagios
sudo groupadd nagcmd
sudo usermod -a -G nagcmd nagios
sudo usermod -a -G nagcmd www-data

Compiling and installing Nagios Core 4.5

Download the latest verified tarball from the official GitHub releases page. Never compile from unverified mirrors. As of mid-2026, version 4.5.9 is the current stable release:

cd /tmp
wget https://github.com/NagiosEnterprises/nagioscore/releases/download/nagios-4.5.9/nagios-4.5.9.tar.gz
tar xzf nagios-4.5.9.tar.gz
cd nagios-4.5.9

./configure --with-httpd-conf=/etc/apache2/sites-available
make all
sudo make install
sudo make install-init
sudo make install-commandmode
sudo make install-config
sudo make install-webconf

The install-config step places sample configurations in /usr/local/nagios/etc/. These are templates only — never deploy them unmodified to production. Enable the Apache site and restart services:

sudo a2ensite nagios.conf
sudo systemctl enable apache2 nagios
sudo systemctl restart apache2 nagios
Nagios Monitoring ArchitectureNagios CoreScheduler + State EngineConfig ParserCheck Pluginscheck_disk, check_httpNRPE AgentRemote Host ExecutionMonitored ServersApp Servers (Laravel/PHP)Database (MySQL/PostgreSQL)Web Servers (Nginx/Apache)Network DevicesNotification HandlersEmail / SMS / SlackEscalation Policies
Nagios monitoring for servers architecture: Core daemon schedules checks via local plugins or remote NRPE agents, then triggers notification handlers based on state changes.

Verifying the installation

Confirm Nagios started correctly and the web interface responds. Check for configuration errors before trusting any output:

sudo /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
sudo systemctl status nagios
curl -u nagiosadmin:YOUR_PASSWORD http://localhost/nagios/cgi-bin/status.cgi

If the verification step reports warnings about deprecated directives, address them immediately. Nagios 4.5 removed several legacy options that older tutorials still reference silently.

How do you configure host and service checks in Nagios?

Nagios uses flat-file configuration organized by object type. The most common mistake I've seen on client projects is putting everything in nagios.cfg directly. Instead, create separate directories for hosts, services, contacts, and commands. Edit /usr/local/nagios/etc/nagios.cfg to include these paths:

cfg_dir=/usr/local/nagios/etc/hosts
cfg_dir=/usr/local/nagios/etc/services
cfg_dir=/usr/local/nagios/etc/contacts
cfg_dir=/usr/local/nagios/etc/commands

Defining monitored hosts

Create a host definition for each server. Use templates to reduce repetition across similar machines. Here's a production-ready template for Laravel application servers running on Ubuntu 24.04:

# /usr/local/nagios/etc/hosts/templates.cfg
define host {
    name                    linux-app-server
    use                     generic-host
    check_period            24x7
    check_interval          5
    retry_interval          1
    max_check_attempts      3
    notification_period     24x7
    notification_options    d,u,r
    contact_groups          admins
    register                0
}

# /usr/local/nagios/etc/hosts/prod-laravel-01.cfg
define host {
    use                     linux-app-server
    host_name               prod-laravel-01
    alias                   Production Laravel App Server
    address                 192.168.10.21
    hostgroups              laravel-apps, production
}

The max_check_attempts directive prevents false positives during brief network hiccups. Setting it to 3 means Nagios must see three consecutive failures before marking the host DOWN. On unreliable networks common in some Nepal regions, increasing this to 4 or 5 reduces alert fatigue significantly.

Configuring service checks with realistic thresholds

Service definitions specify what to monitor on each host. Avoid using default warning/critical thresholds blindly — they rarely match real workload characteristics. For a WooCommerce store handling 200 concurrent users, disk space warnings at 80% may be too aggressive if nightly backups temporarily consume space:

# /usr/local/nagios/etc/services/prod-laravel-01-services.cfg
define service {
    use                     generic-service
    host_name               prod-laravel-01
    service_description     Root Disk Space
    check_command           check_local_disk!20%!10%!/
    check_interval          10
    retry_interval          2
}

define service {
    use                     generic-service
    host_name               prod-laravel-01
    service_description     PHP-FPM Process Count
    check_command           check_nrpe!check_procs_php_fpm
    check_interval          2
    retry_interval          1
    max_check_attempts      4
}

Custom NRPE commands belong in /etc/nagios/nrpe.cfg on the remote host. Define meaningful thresholds there rather than hardcoding values in the Nagios server config. This keeps tuning localized to the machine being monitored.

Service Check Execution FlowSchedulerInterval TimerPlugin ForkExecutes CheckLocal Plugincheck_disk, check_loadRemote NRPEcheck_procs, customExit Code + Output0=OK, 1=WARN, 2=CRITState Database + Event BrokerUpdates Status, Triggers NotificationsLogs to nagios.log
Nagios service check flow: Scheduler forks plugin processes locally or via NRPE, collects exit codes, updates state database, and triggers notifications on state transitions.

What are the essential Nagios plugins for production server monitoring?

The official Nagios Plugins package covers basics, but production environments need additional checks tailored to actual workloads. Install the standard set first, then add specialized plugins as needed:

cd /tmp
wget https://nagios-plugins.org/download/nagios-plugins-2.4.12.tar.gz
tar xzf nagios-plugins-2.4.12.tar.gz
cd nagios-plugins-2.4.12
./configure --with-nagios-user=nagios --with-nagios-group=nagios
make && sudo make install

Critical plugins beyond basic ping and disk

  • check_mysql_query: Validates database responsiveness by executing a lightweight SELECT. More reliable than TCP port checks for detecting locked tables or connection pool exhaustion on Laravel applications.
  • check_http with regex: Confirms application responses contain expected content, not just HTTP 200 status. Catches blank pages from PHP fatal errors that return success codes.
  • check_cert_expiry: Monitors SSL certificate expiration. Let's Encrypt renewals occasionally fail silently; catching expiry 14 days early prevents outages.
  • check_systemd_service: Verifies systemd units are active and not in failed state. Essential for PHP-FPM, Nginx, Redis, and queue workers.
  • check_queue_length: Custom plugin for Laravel/Symfony queue backlogs. A growing queue often indicates worker crashes before users notice delayed emails or processing.

Writing custom plugins safely

Custom plugins must follow the Nagios plugin API contract exactly: exit 0 for OK, 1 for WARNING, 2 for CRITICAL, 3 for UNKNOWN. Always output human-readable text after the pipe character for performance data parsing. Here's a minimal bash plugin checking Laravel queue backlog:

#!/bin/bash
# check_laravel_queue.sh
QUEUE_COUNT=$(php /var/www/app/artisan queue:monitor --format=json | jq '.pending')
WARN_THRESH=${1:-100}
CRIT_THRESH=${2:-500}

if [ "$QUEUE_COUNT" -ge "$CRIT_THRESH" ]; then
    echo "CRITICAL - Queue backlog: $QUEUE_COUNT jobs | pending=$QUEUE_COUNT;$WARN_THRESH;$CRIT_THRESH"
    exit 2
elif [ "$QUEUE_COUNT" -ge "$WARN_THRESH" ]; then
    echo "WARNING - Queue backlog: $QUEUE_COUNT jobs | pending=$QUEUE_COUNT;$WARN_THRESH;$CRIT_THRESH"
    exit 1
else
    echo "OK - Queue backlog: $QUEUE_COUNT jobs | pending=$QUEUE_COUNT;$WARN_THRESH;$CRIT_THRESH"
    exit 0
fi

Test every custom plugin manually before adding it to Nagios configuration. Run it as the nagios user to catch permission issues that won't appear when testing as root.

How does Nagios compare to Prometheus and Zabbix for server monitoring in 2026?

Choosing between monitoring systems depends heavily on team expertise, infrastructure scale, and operational preferences. Teams evaluating DevOps automation in Nepal should weigh these trade-offs carefully before committing to a platform.

CriteriaNagios CorePrometheus + GrafanaZabbix
Setup ComplexityModerate (manual config files)High (multi-component, YAML)Low-Moderate (web UI driven)
Learning CurveSteep initially, shallow afterSteep (PromQL, exporters)Moderate (GUI-heavy)
Auto-DiscoveryNo (manual only)Limited (service discovery)Yes (network scanning)
Resource UsageVery Low (<256MB RAM)High (TSDB storage)Moderate (database backend)
Alerting ModelPoll-based, threshold-drivenPush/pull, rule-based queriesPoll-based, flexible triggers
VisualizationBasic (CGI web interface)Excellent (Grafana dashboards)Good (built-in graphs)
Best ForSmall-medium static infraCloud-native, microservicesEnterprise mixed environments
Nepal SME SuitabilityHigh (low cost, simple hosting)Medium (requires expertise)Medium-High (GUI helps)

Nagios wins when you have fewer than 50 servers, stable topology, and limited DevOps staff. Its configuration-as-code approach means version control works naturally. Prometheus excels for dynamic cloud environments where services appear and disappear frequently. Zabbix offers a middle ground with better auto-discovery than Nagios but lower resource overhead than full Prometheus stacks.

Monitoring Platform Decision TreeStart: Infrastructure Size?< 50 Servers50–500 Servers> 500 / Cloud-NativeNagios CoreLow overhead, manual configZabbixAuto-discovery, GUI mgmtPrometheusMetrics-first, scalableStatic topologyMixed envDynamic/K8s
Decision framework for selecting Nagios monitoring for servers versus Prometheus or Zabbix based on infrastructure scale and operational maturity.

How do you maintain and troubleshoot Nagios in production?

Nagios deployments degrade silently without disciplined maintenance. Configuration drift, stale objects, and unchecked log growth cause more outages than software bugs. Budget-conscious teams exploring website maintenance costs in Nepal should factor monitoring upkeep into annual planning.

Routine maintenance checklist

  1. Weekly configuration validation: Run nagios -v nagios.cfg after every change. Automate this in CI/CD pipelines if configs live in Git.
  2. Monthly log rotation audit: Verify /usr/local/nagios/var/nagios.log rotates properly. Unrotated logs consume disk and slow CGI performance.
  3. Quarterly threshold review: Compare alert frequency against actual incidents. Chronic warnings without action indicate misconfigured thresholds, not real problems.
  4. Biannual plugin updates: Security patches for plugins arrive independently of Nagios Core. Subscribe to the nagios-plugins announce list.
  5. Annual disaster recovery test: Restore Nagios from backup to a fresh VM. Documented procedures that haven't been tested are fiction.

Common production issues and fixes

Stale host states after restart: Nagios retains state in retention.dat. If this file corrupts, all hosts reset to PENDING. Back it up alongside configs. Enable retain_state_information=1 and use_retained_program_state=1 in nagios.cfg.

Slow web interface: CGI performance degrades with large status.dat files. Enable the NDOUtils broker module to offload status queries to MySQL. Alternatively, migrate read-heavy dashboards to Grafana connected via the Nagios API.

False critical alerts during maintenance: Use scheduled downtime windows via the web UI or API. Never disable checks entirely — this hides real failures occurring during the maintenance window.

NRPE connection refused: Usually firewall or allowed_hosts misconfiguration. Test connectivity with check_nrpe -H hostname from the Nagios server before editing nrpe.cfg. Remember that NRPE binds only to interfaces specified in its config.

Implementing Reliable Nagios Monitoring for Servers

Nagios monitoring for servers delivers predictable, auditable infrastructure visibility when configured with discipline. Start with core host and service checks, validate thresholds against real traffic patterns, and establish maintenance routines before scaling to hundreds of checks. The initial configuration investment pays dividends through reduced incident response time and eliminated surprise outages. If your team needs hands-on assistance setting up Nagios or migrating from an existing monitoring solution, reach out to discuss your infrastructure monitoring requirements.

Frequently Asked Questions

Nagios is an open-source infrastructure monitoring system that tracks server health, services, and network devices via plugins, alerting administrators when thresholds are breached or systems fail.

Nagios Core is free and open-source (GPL). Enterprise support or Nagios XI licenses start around USD 1,995 annually (~NPR 265,000), but most self-hosted deployments use Core without licensing fees.

Choose Nagios when you need proven host/service checks with minimal configuration overhead, especially in traditional Linux/PHP environments where plugin ecosystems matter more than time-series metrics.

Nagios Core runs on Ubuntu 22.04 or 24.04 LTS with Apache and PHP 8.2+. A basic monitoring node needs 2 vCPUs, 4GB RAM, and 40GB SSD for up to 500 hosts. In my experience managing legal-tech portals like Court Marriage In Nepal, this spec handles steady-state loads comfortably, though database-heavy setups benefit from separating MySQL onto dedicated hardware. Always compile against current OpenSSL and verify mod_rewrite is enabled before starting installation.

Install prerequisites via apt including build-essential, apache2, php8.2, and libgd-dev. Download the latest stable tarball from nagios.org, extract, run configure with --with-command-group=nagcmd, then make all and make install. Create the nagios user and group, set permissions on /usr/local/nagios, and enable the Apache config symlink. On production servers I maintain, I always pin PHP versions explicitly rather than relying on metapackages to avoid accidental upgrades breaking the web interface during routine maintenance cycles.

Edit contacts.cfg to define notification commands using sendmail or an SMTP relay. For reliable delivery on Ubuntu servers, configure s-nail or msmtp with authenticated SMTP credentials instead of local sendmail, which often gets blocked by cloud providers. Set notification_options to w,u,c,r for warnings, unknowns, critical states, and recovery. Test with a forced service failure before trusting production alerts. I have seen too many silent failures because teams configured contacts but never validated actual mail delivery end-to-end during initial setup.

Yes, using NRPE (Nagios Remote Plugin Executor) over TLS or SSH tunneling. Never expose NRPE port 5666 publicly without encryption. Configure allowed_hosts strictly in nrpe.cfg and use certificate-based authentication where possible. On client projects spanning multiple data centers, I wrap NRPE calls through SSH tunnels to avoid opening additional firewall ports entirely. This adds slight latency but eliminates attack surface exposure, which matters significantly when monitoring legal-tech platforms handling sensitive document workflows across distributed infrastructure.

Write executable scripts returning exit codes 0-3 with stdout performance data. Place them in /usr/local/nagios/libexec/, set ownership to nagios:nagios, and define command objects in commands.cfg referencing $USER1$ macro. Validate syntax with check_command before assigning to services. Most real-world gaps involve business-specific checks like Laravel queue depth or WooCommerce order processing lag. I regularly write Bash or Python wrappers around application APIs because generic plugins rarely capture domain-specific failure modes that actually impact users or revenue streams.

This typically stems from incorrect file ownership after updates or SELinux/AppArmor restrictions. Verify /usr/local/nagios/sbin and cgi-bin directories are owned by nagios:nagios with 755 permissions. Check Apache error logs for specific denials. On Ubuntu 24.04, AppArmor profiles sometimes block CGI execution post-upgrade. Run aa-status to confirm enforcement mode. In one deployment troubleshooting session, the fix was simply reapplying chown -R nagios:nagios /usr/local/nagios after a Composer dependency update had inadvertently reset ownership on shared storage volumes mounted into the monitoring path.

Implement flap detection with low_flap_threshold and high_flap_threshold directives in service definitions. Use max_check_attempts greater than 1 to require consecutive failures before alerting. Add retry intervals longer than normal check intervals. Define dependencies so child service failures suppress parent notifications. False positives erode trust faster than missed incidents. On production eCommerce systems, I tune thresholds seasonally because Dashain traffic spikes trigger baseline violations that are actually normal operational behavior, not genuine outages requiring 3AM pager duty responses.

Nagios Core monitors containers indirectly via host-level metrics or API queries to Docker daemon and Kubernetes API server. Native container awareness requires third-party plugins like check_docker_container or kube-nagios. For pure container orchestration environments, Prometheus usually fits better. However, hybrid setups running legacy PHP-FPM applications alongside containerized microservices benefit from Nagios as the unified alerting layer. I have used this pattern on migration projects where gradual modernization means both architectures coexist for months or years during transition periods.

Version control everything under /usr/local/nagios/etc in Git with automated commits after validated changes. Backup MySQL databases separately if using ndoutils. Store retention policies and historical RRD files independently from configuration. Before any major change, export running config via nagios -v to validate syntax. On sister sites sharing Deployer 7 pipelines, I treat Nagios configs identically to application code with branch protection and peer review. Configuration drift causes more monitoring outages than software bugs in my experience maintaining multi-site infrastructure.

Restrict web interface access via IP whitelisting or VPN. Disable unused CGI modules. Enforce HTTPS with valid certificates. Keep plugins updated since they execute with elevated privileges. Audit sudoers entries for nagios user. Isolate the monitoring server from production databases. Never store plaintext credentials in config files; use environment variables or secret managers. Legal-tech clients demand compliance rigor, so I apply CIS benchmarks to Nagios hosts just as strictly as application servers, because compromised monitoring infrastructure provides attackers complete visibility into defensive blind spots.

Nagios requires self-hosting expertise but costs only server resources (~NPR 3,000/month for basic VPS). Datadog charges per host plus feature add-ons, easily exceeding USD 30/host monthly (~NPR 4,000). For five servers, annual savings exceed NPR 200,000 with Nagios. Trade-offs include manual maintenance versus managed convenience. Small Nepali businesses I work with typically cannot justify SaaS monitoring budgets until reaching 20+ hosts. Until then, invested engineering time in Nagios pays dividends through deeper infrastructure understanding and zero vendor lock-in during growth phases.

Running too many active checks per poll cycle overwhelms the scheduler. Passive checks via NSCA reduce load significantly. Avoid regex in service descriptions. Tune check_result_reaper_frequency and max_concurrent_checks based on CPU cores. Move RRD storage to fast NVMe. Profile slow plugins individually. Scale horizontally with distributed polling before vertically upgrading single nodes. On a directory platform monitoring 800+ endpoints, switching 60% of checks to passive submission dropped average latency from 45 seconds to under 8 seconds without hardware investment, proving architecture trumps raw compute for sustainable scaling.

Share this article

Quick Contact Options
Choose how you want to connect me: