Skip to content

About

Automated LNMP stack builder for Ubuntu — compile-from-source Nginx, MySQL/MariaDB, PHP with auto-tuning

Resources

Stars

10 stars

Watchers

1 watching

Forks

Latest commit

 

History

117 Commits

Folders and files

Repository files navigation

LNMP Stack

Automated LNMP (Linux + Nginx + MySQL/MariaDB + PHP) environment builder for Ubuntu servers.

All software compiled from source or installed via official binaries — no third-party mirrors, no vendor lock-in.

Features

  • Ubuntu-only — Supports Ubuntu 26.04 LTS (recommended), 24.04 LTS, and 22.04 LTS
  • Reproducible source builds — Nginx and PHP compile from HTTPS sources pinned by version and SHA-256; Nginx embeds the repository-pinned OpenSSL security baseline
  • Auto-tuning — Nginx workers, file cache, MySQL InnoDB buffer pool, PHP-FPM children automatically calculated based on host CPU/RAM
  • System hardening — TCP BBR, sysctl tuning, journald log limits, swap auto-creation
  • Modern MIME types — Installation-managed Nginx mime.types includes .mjs, .webmanifest, .wasm, source maps, JSON-LD, modern images, fonts, audio, and video
  • Timezone unified — Single Timezone setting applied across system, PHP, and MySQL
  • IP protection — Auto-generated catch-all server block prevents SSL certificate leakage via IP access
  • PHP extension framework — Registry-based PECL extension compilation
  • Batch extension install — Pre-configure extensions in config, built automatically during installation
  • Tools included — Composer and WP-CLI are installed by default; Docker can be enabled in config
  • SSL management — Let's Encrypt via acme.sh, self-signed certs, expiry monitoring
  • Security hardening — SSH hardening, optional fail2ban/firewall, per-vhost open_basedir
  • systemd native — All services managed via systemd with auto-restart on failure
  • Verified official sources — Every fetched source/tool uses an immutable version or commit plus a required SHA-256 digest
  • Upgrade planning — Inventory old installations, select outdated components, compile/deploy, validate services, and retain rollback copies
  • Non-interactive mode — install.sh --auto, lnmp --yes, and env flags for fully automated deployment (cloud-init / Terraform ready)

Supported OS

OS Version Status
Ubuntu 26.04 LTS (Resolute) ✅ Recommended
Ubuntu 24.04 LTS (Noble) ✅ Supported
Ubuntu 22.04 LTS (Jammy) ✅ Supported

The recommended path is validated on Ubuntu 26.04.1 amd64 with the default MariaDB engine, Nginx/OpenSSL and PHP source builds, the default PECL extensions, Composer/WP-CLI, service runtime checks, and lnmp upgrade plan. Oracle MySQL remains intentionally blocked on 26.04 as documented below.

Full lnmp and db installs currently require x86_64 / amd64 because the database engines are installed from official x86_64 binary tarballs. The nginx target can run on aarch64, but database installation will stop with a clear error instead of installing an incompatible binary.

Software Stack

Software Version Install Method
Nginx 1.30.7 Compile
OpenSSL 3.5.9 + official security patches through 2026-11-17 Embedded in Nginx
MariaDB 11.4.13 LTS Official binary (default)
MySQL 8.4.13 LTS Official binary (not supported on Ubuntu 26.04)
PHP 8.4.28 (fresh install) Compile
Redis 8.10.3 Compile (optional)
Memcached 1.6.45 Compile (optional)
Composer 2.11.2 Verified PHAR
WP-CLI 2.12.0 Verified PHAR
acme.sh 3.1.6 Verified official tarball

The Nginx and PHP security baseline was reviewed on 2026-11-21. Nginx 1.30.7 fixes the nine vulnerabilities disclosed on 2026-11-18, including the major HTTP/2 flow-control and TLS request-body issues. Fresh installations use PHP 8.4.28. Existing PHP 8.2, 8.3, 8.4, and 8.5 installations upgrade to the pinned latest patch in their current release series (8.2.36, 8.3.37, 8.4.28, and 8.5.13 respectively) rather than crossing a release-series boundary. Source archives and their SHA-256 digests are pinned in versions.conf.

PHP 8.4.28 contains the complete CVE-2026-115560 fix. LNMP continues to deploy session.upload_progress.enabled=0 as defense in depth. Fresh installs do not publish a phpinfo.php, and PHP upgrades remove the exact file generated by older LNMP releases. phpMyAdmin is not installed: the current 5.2.3 release has publicly disclosed vulnerabilities without a fixed upstream release.

Quick Start

git clone https://github.com/nczz/lnmp-stack.git
cd lnmp-stack

# Create your local config (overrides lnmp.conf defaults)
cat > lnmp.conf.local << 'EOF'
Timezone='Asia/Taipei'
MySQL_Root_Password='your_secure_password'
PHP_Extensions_Install='redis imagick apcu'
EOF

# Install full stack
sudo ./install.sh lnmp

# Or non-interactive (cloud-init / Terraform ready)
sudo ./install.sh --auto lnmp

Note: Do not edit lnmp.conf directly — it will be overwritten by git pull. Always use lnmp.conf.local for your customizations. It is gitignored and persists across updates.

Configuration

All settings are documented with comments in lnmp.conf. Create lnmp.conf.local to override any value.

Load order: versions.conf → lnmp.conf (defaults) → lnmp.conf.local (your overrides)

Database

Parameter Default Description
DB_Type mariadb Database engine: mariadb or mysql
MySQL_Data_Dir /usr/local/mysql/var MySQL data directory
MariaDB_Data_Dir /usr/local/mariadb/var MariaDB data directory
MySQL_Root_Password (auto-generated) Root password. If not set, a random one is generated and saved to .local

On Ubuntu 26.04, DB_Type='mysql' is blocked by default because Oracle's official MySQL 8.4 binary client tools still require libncurses.so.5 and libtinfo.so.5, which are not available from Ubuntu 26.04 repositories. Use the default DB_Type='mariadb' for Ubuntu 26.04. MySQL remains available for older supported Ubuntu releases where its binary dependencies can be satisfied.

Nginx

Parameter Default Description
Nginx_Modules_Options (empty) Extra compile options, e.g. --add-module=/path
Enable_Nginx_Openssl y Compile with latest OpenSSL (HTTP/2, HTTP/3, TLS 1.3)
Enable_Nginx_Lua n Compile with Lua module (for WAF, custom logic)
Memory_Allocator jemalloc Memory allocator: jemalloc or none

PHP

Parameter Default Description
PHP_Modules_Options (empty) Extra compile options, e.g. --with-pgsql
Enable_PHP_Exif y Image EXIF metadata reading
Enable_PHP_Fileinfo y File MIME type detection
Enable_PHP_Ldap y LDAP directory access
Enable_PHP_Bz2 y Bzip2 compression
Enable_PHP_Sodium y Modern cryptography (libsodium)
Enable_PHP_Imap n Legacy alias that queues the PECL imap extension
PHP_Extensions_Install redis imagick apcu PECL extensions to compile after install
PHP_FPM_DISABLE_FUNCTIONS exec,passthru,shell_exec,system,popen,proc_open,pcntl_exec,pcntl_fork PHP-FPM-only process controls; CLI remains unrestricted for WP-CLI and Composer

PHP 8.4 moved IMAP out of PHP core and into PECL. Prefer PHP_Extensions_Install='redis imagick apcu imap'; existing Enable_PHP_Imap='y' overrides are treated as a compatibility alias and queue the same PECL extension during full installs. LNMP also enforces session.upload_progress.enabled=0 in 99-lnmp-security.ini for fresh installs and PHP upgrades.

Fresh installs keep CLI disable_functions empty, set enable_dl=Off, and apply PHP_FPM_DISABLE_FUNCTIONS only to the [www] pool through php_admin_value. The default blocks external process creation without disabling filesystem, logging, socket, or IMAP functions commonly needed by managed WordPress plugins. Values must be unique comma-separated PHP function names without spaces. Existing installations remain operator-owned and are not silently rewritten during an upgrade; change their active php-fpm.conf deliberately, run php-fpm -t, then reload PHP-FPM after application smoke.

Tools

Parameter Default Description
Enable_Composer y PHP dependency manager
Enable_Docker n Docker + Docker Compose
Enable_WP_CLI y WordPress command-line tool

System

Parameter Default Description
Timezone Asia/Taipei Applied to system, PHP, and MySQL
Default_Website_Dir /home/wwwroot/default Default website root
Enable_Swap y Auto-create swap when RAM < 2GB
Auto_Install n Skip prompts (set automatically by --auto flag)

Security

Parameter Default Description
Enable_Fail2ban n SSH + Nginx brute-force protection
Firewall iptables ufw, iptables, or n (disabled). Firewall modes open IPv4/IPv6 SSH, HTTP, and HTTPS.
Acme_Email (empty) Email for Let's Encrypt/acme.sh registration. Optional (used only for expiry notices). Enables unattended SSL issuance. Can also be set via ACME_EMAIL env.

Auto-Tuning

Configs are automatically optimized based on server specs:

Parameter Formula
Nginx worker_processes = CPU cores
Nginx worker_connections = CPU cores × 1024 (max 65535)
Nginx open_file_cache max 50K ~ 900K based on RAM
Nginx mime.types Project-managed modern MIME map deployed at install time
MySQL innodb_buffer_pool_size = 50% of RAM (min 128M)
MySQL max_connections 64 ~ 512 based on RAM
PHP-FPM pm.max_children = 30% of RAM ÷ 40MB per child
PHP memory_limit 64M ~ 512M based on RAM

System Initialization

The installer automatically configures the host environment:

  • TCP BBR — Enables BBR congestion control
  • sysctl tuning — TCP fastopen, keepalive, port range, file limits, swappiness
  • journald limits — 100M total, 20M per file to prevent log bloat
  • ulimit — nofile/nproc set to 65535
  • Swap — Auto-created when RAM < 2GB
  • sudo NOPASSWD — Enabled for sudo group
  • Timezone — System, PHP, and MySQL all set from single config value

Install Modes

sudo ./install.sh lnmp          # Full stack: Nginx + MySQL + PHP
sudo ./install.sh nginx         # Nginx only
sudo ./install.sh db            # Database only
sudo ./install.sh --auto lnmp   # Non-interactive

Service Management

Bash completion is installed automatically — press Tab to autocomplete commands and options.

lnmp start                # Start all services
lnmp stop                 # Stop all services
lnmp restart              # Restart all services
lnmp reload               # Reload Nginx + PHP-FPM configs
lnmp status               # Show service status with versions
lnmp kill                 # Force kill all LNMP processes

Version Inventory and Upgrades

# Read-only; root is not required.
lnmp upgrade inspect
lnmp upgrade plan

# Adopt an older lnmp-stack runtime after inspect passes. This records actual
# runtime state and a protected configuration/build manifest; it does not
# replace binaries or active configuration.
sudo lnmp --yes upgrade adopt

# Compile/deploy selected installed components.
sudo lnmp --yes upgrade apply nginx php

# Apply installed patch-level updates marked OUTDATED. Missing optional
# components and release-series transitions remain unchanged.
sudo lnmp --yes upgrade apply outdated

# Preview or perform safe cleanup. Transient source/build cache is removable;
# pending, rolled-back, failed, and unclassified backups are never pruned.
sudo lnmp --yes upgrade cleanup --dry-run
sudo lnmp --yes upgrade cleanup

# REVIEW means a release-series transition. Inspect application compatibility,
# then approve that component explicitly.
sudo lnmp --yes upgrade apply php

Selectable components:

nginx php db redis memcached composer wp-cli acme
ext:redis ext:imagick ext:apcu ext:swoole ext:memcached ext:imap
phpmyadmin (legacy vulnerable deployment removal only)

inspect checks OS and architecture, systemd ownership and MainPID binaries, native Nginx/PHP-FPM configuration tests, effective PHP configuration and scan directories, dynamic extensions, free space, and the normal version plan. adopt requires that preflight to pass, then records detected runtime versions and a root-only manifest with build arguments and configuration hashes. It does not rewrite active service or application files.

plan compares runtime versions with versions.conf, checks the recorded OpenSSL patch-set marker for Nginx, and verifies the PHP upload-progress and public-phpinfo.php mitigations. Nginx, PHP, and database release-series changes plus Redis major-version changes are marked REVIEW; outdated never implicitly applies them. Explicitly selecting that component records the operator's approval and proceeds. The plan prints the actual PHP configuration and scan directories, active dynamic extension directives, and any unmanaged extension that would block a PHP replacement.

Before downloading or compiling, apply rejects a service whose systemd MainPID does not execute the expected managed binary, invalid live configuration, a PHP configuration-root or scan-directory layout that needs an explicit migration, and less than 5 GiB free on any filesystem holding the repository build cache, /usr/local staging area, or protected backup directory. These checks run before runtime files are changed.

apply recompiles source components, validates the changed service, and restores the previous binary/prefix when validation fails. PHP patch upgrades retain same-ABI extension binaries, including custom loaders, and require the exact pre-upgrade module inventory afterward. A reviewed PHP release-series transition rebuilds project-supported extensions and rejects unmanaged ones before mutation. Before compiling PHP, hosts with less than 4 GiB of RAM plus swap receive a root-only temporary swap file sized to meet that build-memory floor. It is not added to fstab; successful, failed, and explicit cleanup paths deactivate and remove it. PHP is installed into a same-filesystem candidate prefix seeded from the active configuration, checked for the exact target version, and swapped into place only after the core build succeeds; PHP-FPM is not stopped during core PHP compilation. Each run writes a root-only log under /var/log/lnmp/. Core rollback copies are stored under /var/backups/lnmp/, carry an explicit completion or rollback status, and rollback service health is checked and reported. A process lock serializes adoption, deployment, and cleanup mutations. Interrupted source downloads resume within bounded retries and are accepted only after the pinned SHA-256 matches. Verified downloads and extracted build trees under src/ are transient and removed after every apply, including failed runs. Legacy phpMyAdmin directories are marked OUTDATED; applying that item creates a protected backup and removes the web-served copy because no fixed upstream release is available.

cleanup always removes the transient source/build cache unless a configured Nginx custom-module path still references it. Completed rollback directories expire after 30 days while at least the newest three are retained. Pending, rolled-back, rollback-failed, symlinked, and legacy unclassified directories are never removed automatically. Use --dry-run before changing retention state; rollback copies needed for an observation window remain intentional, root-only data rather than temporary residue.

An upgrade preserves operator-owned active configuration instead of regenerating it from fresh-install templates. Nginx/Redis configuration, database defaults, applicable systemd units, PHP php.ini, php-fpm.conf, pool files, and extension INI tuning are copied into the protected rollback area and compared before the upgraded service is accepted. PHP additionally records before/after module inventories and a root-only php-config.diff. Every previously loaded module must remain available. A reviewed PHP release-series transition may update the project-managed php.d/99-lnmp-security.ini overlay and migrate an extension_dir value that exactly matches the previous effective extension directory to the new compiled ABI directory. Same-series patch upgrades preserve the active configuration byte-for-byte. Both paths cover legacy installations whose original compile, configuration, or scan prefix differs from /usr/local/php.

Before a PHP build, dynamic extension directives and loaded modules are inventoried. Same-series patch upgrades preserve the compatible ABI directory and verify the exact module inventory, including unmanaged custom extensions. For a release-series transition, extensions registered in lib/extensions.sh are rebuilt against the new PHP API without overwriting existing INI tuning; an unmanaged extension such as a custom loader or debugger blocks the upgrade before binaries change. Add pinned source/build metadata and tests rather than silently dropping the capability.

Existing virtual hosts, certificates, webroots, and database data directories remain in place. Before an Nginx build, the upgrader inspects the current nginx -V module arguments and refuses to remove an untracked custom module; add that exact option to Nginx_Modules_Options in lnmp.conf.local first. Redis readiness checks honor the configured TCP port or Unix socket and treat an authentication challenge as proof that the server finished loading without exposing credentials.

Database upgrades require /root/.my.cnf. Before changing binaries, the command writes a compressed --all-databases logical dump under /var/backups/lnmp/. The previous database binary prefix is retained beside the live prefix. A failed deployment attempts binary rollback, but database metadata changes can be one-way; retain the logical dump until application checks pass. Custom data directories remain in place.

Virtual Host Management

# HTTP-01 remains the default.
lnmp vhost add example.com --rewrite wordpress --ssl --redirect

# DNS-01 is explicit and supports wildcard aliases.
lnmp vhost add example.com --domains "*.example.com" --ssl \
  --challenge dns --dns-provider dns_cf \
  --dns-credentials /etc/lnmp/cloudflare-dns.env --redirect

lnmp vhost del example.com
lnmp vhost list

Options include --domains, --webroot, --rewrite, --ssl, --challenge, --dns-provider, --dns-credentials, --dns-sleep, and --redirect.

SSL Certificate Management

HTTP-01 stays backward-compatible and is the default:

lnmp ssl install example.com

DNS-01 is opt-in. It does not require port 80, an existing vhost, or A/AAAA records pointing at this host, and it can issue wildcard certificates:

install -d -m 700 /etc/lnmp
install -m 600 /dev/null /etc/lnmp/cloudflare-dns.env
printf '%s\n' 'CF_Token=REPLACE_WITH_ZONE_SCOPED_TOKEN' \
  > /etc/lnmp/cloudflare-dns.env

lnmp --yes ssl install example.com --domains "*.example.com" \
  --challenge dns --dns-provider dns_cf \
  --dns-credentials /etc/lnmp/cloudflare-dns.env
Provider Hook Required credential source
Cloudflare dns_cf CF_Token; optional CF_Account_ID, CF_Zone_ID
AWS Route53 dns_aws AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY, or ECS/EC2 IAM role
Alibaba Cloud DNS dns_ali Ali_Key + Ali_Secret
DNSPod.cn dns_dp DP_Id + DP_Key

The credentials file is parsed as literal, unquoted NAME=value records; it must be a non-symlink regular file owned by the operator and inaccessible to group/others. Provider credentials are never accepted as CLI values or printed by LNMP. acme.sh persists the credentials needed for unattended renewal under its root-only home. Manual DNS mode is intentionally unsupported because it cannot renew automatically.

lnmp ssl renew                         # Repair managed vhosts, then renew all
lnmp ssl renew example.com             # Repair managed vhosts, then renew one
lnmp ssl revoke example.com            # Revoke and remove certificate
lnmp ssl list                          # List certs with expiry
lnmp ssl self example.com              # Self-signed cert; copies vhost aliases
lnmp ssl self example.com --domains "www.example.com"
lnmp --yes ssl repair                  # Migrate legacy HTTP-01 vhost layouts

HTTPS redirects use a server-level request-URI guard that excludes /.well-known/acme-challenge/ before returning 301; they do not create a second location / that could conflict with WordPress or other rewrite rules. The ACME challenge also has an explicit higher-priority location in both HTTP and HTTPS server blocks. This keeps renewal reachable after cached authorizations expire. ssl repair migrates existing project-generated vhosts atomically, runs nginx -t, reloads only valid configuration, and restores the originals on failure. It prints the root-only backup directory under /var/backups/lnmp/. ssl renew runs the same idempotent repair before invoking acme.sh.

Self-signed certificates include the primary domain and aliases as SANs. When --domains is omitted, aliases come from the existing vhost's first server_name; an existing HTTPS block is reconciled instead of skipped.

  • Uses Let's Encrypt as default CA
  • EC-256 key type by default
  • HTTP-01 remains the default; DNS-01 must be selected explicitly
  • ACME account/domain configuration is restricted to mode 600
  • HTTPS catch-all with ssl_reject_handshake prevents cert leakage via IP

Agent / Non-Interactive Usage

All vhost, ssl, and db subcommands are safe to drive from AI agents, CI, cloud-init, or ssh host 'cmd' — they never hang on a prompt. The same commands still prompt interactively when run from a real terminal, so human and automated use share one code path.

See command-specific help (lnmp --help, lnmp vhost add --help, lnmp ssl --help, lnmp ssl install --help, lnmp db --help, and lnmp db add --help) plus AGENTS.md for the full operating contract (SSL preconditions, exit codes, recipes).

# Force non-interactive mode (any one of these):
lnmp --yes vhost add site.com --rewrite wordpress --ssl --redirect
LNMP_ASSUME_YES=1 lnmp ssl install site.com
NONINTERACTIVE=1 lnmp db add mydb myuser --password-file /root/.lnmp-mydb.pass

Behavior in non-interactive mode:

  • Missing or invalid required values exit with a sysexits code on stderr instead of hanging: 64 = bad/missing/invalid argument, 69 = dependency unavailable, 75 = transient (retry).
  • Optional values fall back to defaults. Supplied domains, webroots, rewrite names, and database identifiers are validated before root-owned files or SQL are touched.
  • acme.sh registration email is read from ACME_EMAIL env or Acme_Email in lnmp.conf.local (email is optional for Let's Encrypt).
  • Composer inventory and verification close stdin, use finite timeouts, set COMPOSER_ALLOW_SUPERUSER=1, and pass --no-interaction, so --auto remains unattended even inside tmux, screen, or another inherited pseudo-terminal.

HTTP-01 preconditions (or issuance returns 75): DNS A/AAAA points here, port 80 is reachable, and the vhost serves /.well-known/acme-challenge/. DNS-01 instead requires a supported provider, least-privilege TXT record credentials (or AWS role), authoritative propagation, and compatible CAA.

Database Management

# CLI mode
install -m 600 /dev/null /root/.lnmp-mysite.pass
printf '%s\n' 'STRONG_PASSWORD_HERE' > /root/.lnmp-mysite.pass
lnmp db add mysite myuser --password-file /root/.lnmp-mysite.pass  # Create database + user
lnmp db del mysite                    # Drop database + user
lnmp db list                          # List databases and users
lnmp db export mysite                 # Export to .sql.gz
lnmp db import mysite backup.sql.gz   # Import (supports .gz)
lnmp --yes db repair-clients           # Reconcile MariaDB/MySQL commands in PATH

# Interactive mode
lnmp db add

# Reset MySQL root password (reads from lnmp.conf.local)
lnmp reset-password

Fresh installs and database upgrades expose MariaDB's current mariadb, mariadb-dump, mariadb-check, mariadb-admin, and mariadb-import names, plus legacy compatibility names. After updating an existing host, run lnmp --yes db repair-clients once so WP-CLI database commands work from login shells, non-interactive SSH, and cron without a custom PATH.

PHP Extensions

# Pre-install via config
PHP_Extensions_Install='redis imagick apcu swoole'

# Or manage later
sudo lnmp addons install redis
sudo lnmp addons install imagick
sudo lnmp addons uninstall swoole
sudo lnmp addons list

# Available: redis, imagick, apcu, swoole, memcached, imap

# Standalone services
sudo lnmp addons install redis-server
sudo lnmp addons install memcached-server

OPcache is compiled and enabled by default. OPcache JIT is intentionally left commented out in opcache.ini because it can trigger runtime bugs on some workloads and PHP extension combinations. Uncomment opcache.jit_buffer_size and opcache.jit only after validating the workload with JIT.

Additional Tools

lnmp upgrade plan                    # Installed/pinned version difference
sudo lnmp upgrade apply outdated     # Conservative patch-level upgrades
sudo lnmp upgrade apply php          # Explicitly approve a REVIEW transition
sudo ./tools/backup.sh [dir]         # Backup DB + sites + configs (7-day retention)
sudo ./tools/uninstall.sh            # Uninstall (backup DB + preserve sites)
sudo ./tools/uninstall.sh --reset    # Full reset for clean reinstall

Directory Layout

Path Description
/usr/local/nginx/ Nginx installation
/usr/local/nginx/conf/vhost/ Virtual host configs
/usr/local/nginx/conf/ssl/ SSL certificates + DH parameters
/usr/local/mysql/ MySQL installation
/usr/local/mysql/var/ MySQL data (configurable)
/usr/local/php/ PHP installation
/usr/local/php/etc/php.d/ PHP extension .ini files
/usr/local/redis/ Redis (if installed)
/usr/local/acme.sh/ acme.sh (Let's Encrypt client)
/home/wwwroot/ Website files
/home/wwwlogs/ All logs (Nginx, PHP, FPM, mail)
/root/.my.cnf MySQL root password (auto-generated)
/root/lnmp-install.log Installation log
/var/log/lnmp/ Root-only per-run upgrade logs
/var/backups/lnmp/ Upgrade rollback copies and database dumps

License

MIT

About

Automated LNMP stack builder for Ubuntu — compile-from-source Nginx, MySQL/MariaDB, PHP with auto-tuning

Resources

Stars

10 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages