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

107 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.6 Compile
OpenSSL 3.5.9 + official 2026-11-10 security patch set 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.27 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 security baseline was reviewed on 2026-11-12. OpenSSL's 2026-11-10 advisory named 3.5.10 as the fixed LTS release, but that artifact was not yet published at the baseline date. The build therefore uses the official 3.5.9 source plus the five official OpenSSL 3.5-branch fix commits, each independently pinned by SHA-256. versions.conf is the authoritative manifest.

PHP 8.4.27 is deployed with session.upload_progress.enabled=0, the upstream mitigation that fully blocks the residual CVE-2026-115560 path pending the next regular PHP bugfix release. 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 plan

# 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

# 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)

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 also prints the PHP configuration-preservation boundary, active dynamic extension directives, and any unmanaged extension that would block a PHP replacement.

apply recompiles source components, rebuilds installed project-supported PHP extensions after a PHP upgrade, validates the changed service, and restores the previous binary/prefix when validation fails. Each run writes a root-only log under /var/log/lnmp/. Core rollback copies are stored under /var/backups/lnmp/, rollback service health is checked and reported, and a process lock prevents concurrent upgrade runs. Legacy phpMyAdmin directories are marked OUTDATED; applying that item creates a protected backup under /var/backups/lnmp/ and removes the web-served copy because no fixed upstream release is available.

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. The only automatically updated PHP configuration is the project-managed php.d/99-lnmp-security.ini security overlay.

Before a PHP build, dynamic extension directives are inventoried. Extensions registered in lib/extensions.sh are rebuilt against the new PHP API without overwriting their existing INI tuning. An unmanaged extension such as a custom loader or debugger blocks the PHP 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