How To Install LEMP Stack on AlmaLinux 10
In this tutorial, we will show you how to install LEMP Stack on AlmaLinux 10. Setting up a robust web development environment requires the right combination of technologies. The LEMP stack represents one of the most powerful and efficient web server configurations available today. This comprehensive guide will walk you through installing and configuring a complete LEMP stack on AlmaLinux 10, transforming your server into a high-performance web hosting platform.
LEMP stack consists of four essential components: Linux operating system, Nginx web server, MySQL/MariaDB database, and PHP scripting language. Unlike traditional LAMP stacks that use Apache, LEMP leverages Nginx’s superior performance characteristics for handling concurrent connections and serving static content. AlmaLinux 10 provides the perfect foundation with its enterprise-grade stability, security features, and Red Hat compatibility.
This tutorial covers everything from initial system preparation to advanced optimization techniques. You’ll learn how to install each component, configure secure database connections, set up virtual hosting, and implement security best practices. Whether you’re deploying WordPress sites, building custom PHP applications, or hosting multiple domains, this guide provides the knowledge needed for a production-ready LEMP environment.
Understanding LEMP Stack Components
What is LEMP Stack
The LEMP stack represents a collection of open-source software designed to serve dynamic web applications efficiently. Each letter corresponds to a specific technology: Linux provides the operating system foundation, Nginx (Engine-X) handles web server responsibilities, MySQL or MariaDB manages database operations, and PHP processes server-side scripting. This combination creates a powerful platform capable of handling everything from simple websites to complex web applications.
Modern web development demands high performance and scalability. LEMP stack addresses these requirements through Nginx’s event-driven architecture, which excels at handling thousands of simultaneous connections with minimal resource consumption. The stack’s modular design allows developers to optimize each component independently, resulting in superior performance compared to traditional alternatives.
Why Choose AlmaLinux 10
AlmaLinux 10 offers enterprise-grade reliability with community-driven development. As a Red Hat Enterprise Linux derivative, it provides long-term stability and extensive security updates. The distribution includes modern package managers, updated system libraries, and optimized performance for server environments. AlmaLinux’s commitment to backward compatibility ensures smooth migrations and consistent behavior across different deployment scenarios.
The latest AlmaLinux release incorporates advanced security features, including enhanced SELinux policies, improved firewall management, and comprehensive audit capabilities. These features make it an ideal choice for production environments where security and compliance are paramount.
LEMP vs LAMP Comparison
While both stacks serve similar purposes, key differences make LEMP preferable for many scenarios. Nginx’s asynchronous processing model handles concurrent connections more efficiently than Apache’s traditional threaded approach. This architecture particularly benefits high-traffic websites and applications requiring real-time features.
LEMP stacks typically consume less memory and CPU resources, making them cost-effective for cloud deployments and resource-constrained environments. The configuration flexibility of Nginx also enables advanced load balancing, SSL termination, and reverse proxy configurations that are more complex to implement with Apache.
Prerequisites and System Preparation
System Requirements
Before beginning the installation process, ensure your AlmaLinux 10 server meets the minimum requirements. You’ll need root or sudo access privileges, a working internet connection for downloading packages, and adequate storage space for the LEMP components. A minimum of 2GB RAM is recommended for optimal performance, though 1GB may suffice for development environments.
Network connectivity is essential for package installation and updates. Verify that your server can reach external repositories and that DNS resolution functions correctly. If operating behind a corporate firewall, ensure necessary ports are accessible for package downloads.
Initial Server Setup
Begin by updating your AlmaLinux 10 system to ensure all packages are current and compatible. This reduces the likelihood of dependency conflicts during LEMP installation:
sudo dnf update -y
Install the EPEL repository to access additional packages not included in the base AlmaLinux repositories:
sudo dnf install epel-release -y
Configure basic firewall settings to prepare for web server access. Open HTTP and HTTPS ports while maintaining security:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
Step 1: Installing and Configuring Nginx Web Server
Installing Nginx
Nginx installation on AlmaLinux 10 utilizes the DNF package manager for straightforward deployment. Execute the following command to install Nginx and its dependencies:
sudo dnf install nginx -y
The installation process automatically creates the necessary directory structure, including configuration files in /etc/nginx/
and document root in /var/www/html/
. Verify the installation by checking the Nginx version:
nginx -v
Understanding Nginx’s directory structure is crucial for effective management. Configuration files reside in /etc/nginx/
, with the main configuration file located at /etc/nginx/nginx.conf
. Virtual host configurations typically go in /etc/nginx/conf.d/
or /etc/nginx/sites-available/
depending on your preference.
Configuring Nginx Service
Start the Nginx service and enable automatic startup on system boot:
sudo systemctl start nginx
sudo systemctl enable nginx
Verify that Nginx is running correctly by checking its status:
sudo systemctl status nginx
The output should indicate that the service is active and running. If you encounter issues, examine the Nginx error logs located at /var/log/nginx/error.log
for troubleshooting information.
Firewall Configuration
With Nginx installed and running, verify that firewall rules allow web traffic. Test the configuration by accessing your server’s IP address through a web browser. You should see the default Nginx welcome page, confirming successful installation and proper firewall configuration.
For servers with SELinux enabled, ensure that web server contexts are properly configured:
sudo setsebool -P httpd_can_network_connect 1
This setting allows Nginx to make network connections, which is essential for reverse proxy configurations and external API calls.
Step 2: Installing and Securing MariaDB Database Server
Installing MariaDB
MariaDB serves as an excellent MySQL alternative, offering enhanced performance and additional features. Install MariaDB server and client packages using DNF:
sudo dnf install mariadb mariadb-server -y
The installation includes MariaDB version 10.11.11 on AlmaLinux 10, providing modern database features and improved security. This version supports advanced storage engines, better JSON handling, and enhanced performance optimization features.
Starting and Enabling MariaDB
Initialize the MariaDB service and configure it for automatic startup:
sudo systemctl enable --now mariadb
sudo systemctl start mariadb
Verify that MariaDB is operational by checking its service status:
sudo systemctl status mariadb
The service should show as active and running. MariaDB logs are available in /var/log/mariadb/
for troubleshooting purposes if needed.
Securing MariaDB Installation
MariaDB includes a security script that removes default vulnerabilities and strengthens the installation. Run the security configuration wizard:
sudo mysql_secure_installation
The script guides you through several security improvements:
- Setting a root password for database access
- Removing anonymous user accounts that pose security risks
- Disabling remote root login to prevent unauthorized access
- Removing the test database and associated privileges
- Reloading privilege tables to apply changes immediately
Choose ‘Y’ for all security options to maximize protection. When prompted for password validation, select a strong password that includes uppercase letters, lowercase letters, numbers, and special characters.
After completing the security wizard, test database connectivity:
mysql -u root -p -e "SHOW DATABASES;"
This command displays available databases, confirming successful installation and configuration.
Step 3: Installing and Configuring PHP
Installing PHP and Essential Modules
PHP-FPM (FastCGI Process Manager) provides optimal integration with Nginx for processing dynamic content. Install PHP along with essential modules:
sudo dnf install php php-fpm php-mysqlnd php-gd php-xml php-mbstring php-curl php-zip -y
These modules provide core functionality:
php-mysqlnd
: MySQL/MariaDB database connectivityphp-gd
: Image processing capabilitiesphp-xml
: XML parsing and manipulationphp-mbstring
: Multibyte string handlingphp-curl
: HTTP client functionalityphp-zip
: Archive file handling
Verify the PHP installation and check the installed version:
php --version
Configuring PHP-FPM
PHP-FPM operates as a separate service that communicates with Nginx through Unix sockets or TCP connections. Start and enable the PHP-FPM service:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
The default PHP-FPM configuration typically works well for most scenarios. However, you can optimize settings in /etc/php-fpm.d/www.conf
for specific performance requirements.
Key configuration parameters include:
pm.max_children
: Maximum number of child processespm.start_servers
: Number of processes to start initiallypm.min_spare_servers
: Minimum idle processespm.max_spare_servers
: Maximum idle processes
Integrating PHP with Nginx
Configure Nginx to process PHP files through PHP-FPM by creating a server block configuration. Create a new virtual host file:
sudo nano /etc/nginx/conf.d/default.conf
Add the following configuration:
server {
listen 80;
server_name your_domain.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
Test the PHP integration by creating a PHP info file:
echo "" | sudo tee /var/www/html/info.php
Restart Nginx to apply the configuration changes:
sudo systemctl restart nginx
Step 4: Configuring Nginx Virtual Hosts
Creating Virtual Host Configuration
Virtual hosting enables multiple websites on a single server, maximizing resource utilization. Create directory structures for each website:
sudo mkdir -p /var/www/example1.com/html
sudo mkdir -p /var/www/example2.com/html
Set appropriate ownership and permissions:
sudo chown -R $USER:$USER /var/www/example1.com/html
sudo chown -R $USER:$USER /var/www/example2.com/html
sudo chmod -R 755 /var/www
Create sample content for testing:
echo "<h1>Welcome to Example1.com</h1>" | sudo tee /var/www/example1.com/html/index.html
echo "<h1>Welcome to Example2.com</h1>" | sudo tee /var/www/example2.com/html/index.html
SSL/TLS Configuration
Secure connections are essential for modern web applications. Generate self-signed certificates for testing purposes:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/nginx-selfsigned.key \
-out /etc/ssl/certs/nginx-selfsigned.crt
Create a strong Diffie-Hellman group for enhanced security:
sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
Configure Nginx to use SSL by adding HTTPS server blocks to your virtual host configurations.
Testing and Validation
Create comprehensive test files to verify LEMP functionality. Test PHP processing with a database connection script:
<?php
$servername = "localhost";
$username = "your_db_user";
$password = "your_password";
$dbname = "test_database";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Restart all services to ensure proper integration:
sudo systemctl restart nginx
sudo systemctl restart php-fpm
sudo systemctl restart mariadb
Database Management and User Creation
Creating Databases and Users
Proper database management involves creating dedicated databases and users for each application. Access the MariaDB console:
mysql -u root -p
Create a new database and user with appropriate privileges:
CREATE DATABASE example_db;
CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
Testing Database Connectivity
Verify database connectivity from PHP by creating a test script:
<?php
$connection = new mysqli("localhost", "example_user", "secure_password", "example_db");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
echo "Database connection successful!";
?>
This confirms that PHP can successfully communicate with MariaDB using the created credentials.
Security Hardening and Best Practices
Server Security
Implement comprehensive security measures to protect your LEMP stack. Configure proper file permissions for web directories:
sudo find /var/www -type d -exec chmod 755 {} \;
sudo find /var/www -type f -exec chmod 644 {} \;
Install and configure fail2ban for brute force protection:
sudo dnf install fail2ban -y
sudo systemctl enable --now fail2ban
Application Security
Secure PHP configuration by editing /etc/php.ini
:
expose_php = Off
display_errors = Off
log_errors = On
allow_url_fopen = Off
allow_url_include = Off
Configure Nginx security headers by adding to your server blocks:
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
Performance Optimization
Nginx Optimization
Optimize Nginx performance by configuring worker processes and connections in /etc/nginx/nginx.conf
:
worker_processes auto;
worker_connections 1024;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript;
PHP and Database Optimization
Enable PHP OPcache for improved performance by adding to /etc/php.ini
:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
Optimize MariaDB by configuring key buffer size and query cache in /etc/my.cnf
:
[mysqld]
key_buffer_size = 256M
query_cache_type = 1
query_cache_size = 64M
Troubleshooting Common Issues
Service-Related Issues
When Nginx fails to start, check configuration syntax:
sudo nginx -t
For PHP-FPM socket connection issues, verify the socket path in both PHP-FPM and Nginx configurations. Ensure they match exactly.
MariaDB connection problems often relate to user privileges or firewall settings. Check the error log at /var/log/mariadb/mariadb.log
for specific error messages.
Configuration Problems
502 Bad Gateway errors typically indicate PHP-FPM communication issues. Verify that PHP-FPM is running and the socket file exists:
sudo systemctl status php-fpm
ls -la /run/php-fpm/www.sock
File permission issues can prevent proper operation. Ensure that the nginx user has appropriate access to web directories and PHP-FPM sockets.
SELinux denials require policy adjustments. Use ausearch
to identify denied operations and create appropriate policies:
sudo ausearch -m avc -ts recent
Congratulations! You have successfully installed LEMP stack. Thanks for using this tutorial for installing LEMP (Nginx, MariaDB, and PHP) Stack on your AlmaLinux OS 10 system. For additional help or useful information, we recommend you check the official LEMP website.