How to Install LEMP Stack on Ubuntu Server 24.04: Complete Guide

Learn how to install and configure LEMP stack (Linux, Nginx, MySQL/MariaDB, PHP) on Ubuntu Server 24.04 with this comprehensive, step-by-step guide. Perfect for developers and system administrators.

Introduction

The LEMP stack is a powerful and efficient web hosting solution that combines Linux, Nginx (pronounced “Engine-X”), MySQL/MariaDB, and PHP. This comprehensive guide will walk you through the complete installation and configuration process on Ubuntu Server 24.04 LTS, ensuring you have a robust development or production environment.

Why Choose LEMP Stack?

The LEMP stack has become increasingly popular for several compelling reasons:

  • Performance: Nginx is known for its high performance and low resource consumption compared to Apache
  • Scalability: The stack components work seamlessly together to handle high-traffic websites
  • Security: Regular updates and a strong community focus on security make it ideal for production environments
  • Flexibility: Support for various programming languages and frameworks beyond PHP
  • Cost-effective: All components are open-source and free to use

Prerequisites

Before beginning the installation process, ensure your system meets these requirements:

  • A fresh installation of Ubuntu Server 24.04 LTS
  • Root access or sudo privileges
  • Active internet connection
  • Basic command line knowledge
  • Minimum system requirements:
    • 2GB RAM (4GB recommended)
    • 20GB storage space
    • 64-bit processor

Step 1: System Preparation

Update System Packages

First, ensure your system is up to date:

sudo apt update
sudo apt upgrade -y

Install Essential Tools

Install required system utilities:

sudo apt install -y software-properties-common curl wget ca-certificates apt-transport-https

Step 2: Installing Nginx

Add Nginx Repository

For the latest stable version:

sudo apt install -y nginx

Verify Installation

Check Nginx status:

sudo systemctl status nginx

Configure Firewall

Allow HTTP and HTTPS traffic:

sudo ufw allow 'Nginx Full'
sudo ufw enable

Basic Nginx Configuration

Create a server block configuration:

sudo vim /etc/nginx/sites-available/your_domain

server {
listen 80;
server_name your_domain.com www.your_domain.com;
root /var/www/your_domain;

index index.php index.html index.htm;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}

location ~ /\.ht {
deny all;
}
}

Enable the configuration:

sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Step 3: Installing MariaDB

Install MariaDB Server

sudo apt install -y mariadb-server mariadb-client

Secure Installation

Run the security script:

sudo mysql_secure_installation

Follow the prompts to:

  • Set root password
  • Remove anonymous users
  • Disallow root login remotely
  • Remove test database
  • Reload privilege tables

Verify MariaDB Installation

Check the service status:

sudo systemctl status mariadb

Step 4: Installing PHP and Required Extensions

Install PHP-FPM and Common Extensions

sudo apt install -y php8.2-fpm php8.2-common php8.2-mysql \
php8.2-xml php8.2-xmlrpc php8.2-curl php8.2-gd \
php8.2-imagick php8.2-cli php8.2-dev php8.2-imap \
php8.2-mbstring php8.2-opcache php8.2-soap php8.2-zip

Configure PHP

Edit PHP configuration for better performance:

sudo vim /etc/php/8.2/fpm/php.ini

Recommended optimizations:

; Maximum upload file size
upload_max_filesize = 64M
post_max_size = 64M

; Maximum execution time
max_execution_time = 300

; Maximum input time
max_input_time = 300

; Memory limit
memory_limit = 256M

; PHP opcache settings
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

Verify PHP Installation

Create a PHP info file:

sudo vim /var/www/your_domain/info.php

Add the following content:

<?php
phpinfo();

Step 5: Testing the LEMP Stack

Create a Test Database

Log into MariaDB:

sudo mysql -u root -p

Create a test database and user:

CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Create a Test PHP Application

sudo vim /var/www/your_domain/test.php

Add the following content:

<?php
$connection = new mysqli('localhost', 'testuser', 'your_password', 'testdb');

if ($connection->connect_error) {
die('Connection failed: ' . $connection->connect_error);
}

echo 'Successfully connected to MariaDB!';

// Test PHP functionality
$phpVersion = phpversion();
echo "<br>PHP Version: " . $phpVersion;

// Test file system
$webRoot = $_SERVER['DOCUMENT_ROOT'];
echo "<br>Web Root: " . $webRoot;

$connection->close();

Step 6: Performance Optimization

Nginx Optimization

Edit Nginx configuration:

sudo vim /etc/nginx/nginx.conf

Add these optimizations:

# Worker processes
worker_processes auto;

# Worker connections
events {
worker_connections 1024;
multi_accept on;
}

http {
# Basic Settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

# Buffer size for POST submissions
client_body_buffer_size 10K;
client_max_body_size 8m;

# Buffer size for Headers
client_header_buffer_size 1k;

# Max time to receive client headers/body
client_body_timeout 12;
client_header_timeout 12;

# Max time to keep a connection open
keepalive_timeout 15;

# Max time for the client accept/receive a response
send_timeout 10;

# Skip buffering for static files
sendfile on;

# Optimize sendfile packets
tcp_nopush on;
}

MariaDB Optimization

Edit MariaDB configuration:

sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf

Add these optimizations:

[mysqld]
# InnoDB Settings
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_method = O_DIRECT
innodb_flush_log_at_trx_commit = 2

# Connection Settings
max_connections = 100
thread_cache_size = 128
table_open_cache = 4000

# Query Cache Settings
query_cache_size = 64M
query_cache_type = 1

# Temporary Table Settings
tmp_table_size = 64M
max_heap_table_size = 64M

Enable Caching

Install and configure Redis for caching:

sudo apt install redis-server php8.2-redis

Edit Redis configuration:

sudo vim /etc/redis/redis.conf

Optimize Redis settings:

maxmemory 256mb
maxmemory-policy allkeys-lru

Step 7: Security Hardening

Nginx Security Measures

Add these security headers to your Nginx configuration:

server {
# ... other configurations ...

# Security headers
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# SSL configuration (if using HTTPS)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
}

PHP Security Settings

Update PHP configuration for better security:

sudo vim /etc/php/8.2/fpm/php.ini

Add these security settings:

; Disable dangerous functions
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

; Hide PHP version
expose_php = Off

; Limit file upload types
upload_max_filesize = 2M
max_file_uploads = 20
upload_tmp_dir = /tmp

; Session security
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1
session.cookie_samesite = "Strict"

MariaDB Security Enhancements

Create a dedicated database user for each application:

CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON application_db.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;

Step 8: Maintenance and Monitoring

Set Up Automated Updates

Create an automatic security updates configuration:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Configure Log Rotation

Edit Nginx log rotation:

sudo vim /etc/logrotate.d/nginx

Add these settings:

/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
prerotate
if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
run-parts /etc/logrotate.d/httpd-prerotate; \
fi \
endscript
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}

Troubleshooting Common Issues

PHP-FPM Issues

  1. PHP-FPM Not Starting # Check PHP-FPM logs sudo tail -f /var/log/php8.2-fpm.log # Verify PHP-FPM socket ls -l /var/run/php/php8.2-fpm.sock # Restart PHP-FPM sudo systemctl restart php8.2-fpm
  2. 502 Bad Gateway Error # Check Nginx error logs sudo tail -f /var/log/nginx/error.log # Verify PHP-FPM pool configuration sudo vim /etc/php/8.2/fpm/pool.d/www.conf

MariaDB Connection Issues

  1. Cannot Connect to Database # Check MariaDB status sudo systemctl status mariadb # Verify connection settings sudo mysql -u root -p # Check user privileges SHOW GRANTS FOR 'user'@'localhost';

Frequently Asked Questions (FAQ)

General Questions

Q: What are the minimum system requirements for LEMP stack? A: For a basic development environment, you need at least 2GB RAM, 20GB storage, and a 64-bit processor. Production environments may require more resources depending on your application’s needs.

Q: How do I secure my LEMP installation? A: Key security measures include:

  • Regularly updating all components
  • Using strong passwords
  • Implementing SSL/TLS
  • Configuring firewalls
  • Following security best practices for each component

Q: Can I install multiple PHP versions? A: Yes, you can install multiple PHP versions and switch between them using the update-alternatives command. However, only one version can be active with PHP-FPM at a time.

Technical Questions

Q: How do I enable SSL/HTTPS? A: Use Let’s Encrypt with Certbot:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com

Q: How do I optimize LEMP stack performance? A: Key optimization steps include:

  • Implementing caching (Redis, OpCache)
  • Optimizing Nginx configuration
  • Tuning MariaDB settings
  • Enabling PHP-FPM process management
  • Using content delivery networks (CDNs)

Conclusion

Installing and configuring a LEMP stack on Ubuntu Server 24.04 provides a robust foundation for web applications. This guide covered essential installation steps, security measures, optimization techniques, and troubleshooting procedures. Regular maintenance and monitoring ensure optimal performance and security.

Remember to:

  • Keep all components updated
  • Regularly backup your data
  • Monitor system resources
  • Follow security best practices
  • Test configurations in development before applying to production
{
"@context": "https://schema.org",
"@type": "TechArticle",
"headline": "How to Install LEMP Stack on Ubuntu Server 24.04: Complete Guide",
"description": "Comprehensive guide for installing and configuring LEMP stack (Linux, Nginx, MySQL/MariaDB, PHP) on Ubuntu Server 24.04 with security best practices and optimization tips.",
"keywords": "LEMP Stack, Ubuntu Server 24.04, Nginx, MariaDB, PHP, Web Server, Installation Guide",
"author": {
"@type": "Organization",
"name": "TechGuides"
},
"datePublished": "2024-01-13",
"dateModified": "2024-01-13",
"publisher": {
"@type": "Organization",
"name": "TechGuides"
},
"articleSection": "System Administration",
"audience": {
"@type": "Audience",
"audienceType": "Developers and System Administrators"
},
"about": {
"@type": "SoftwareApplication",
"name": "LEMP Stack",
"operatingSystem": "Ubuntu Server 24.04",
"applicationCategory": "Web Server"
}
}
Next Article

How to Prevent Brute Force Attacks in WordPress: The Ultimate Security Guide

View Comments (1)

Leave a Comment

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

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨