FedoraRHEL Based

How To Install LEMP Stack on Fedora 42

Install LEMP Stack on Fedora 42

In this tutorial, we will show you how to install LEMP on Fedora 42. The LEMP stack represents a powerful combination of software components that work together to deliver dynamic websites and web applications. If you’re looking to set up a robust web server environment on Fedora 42, installing a LEMP stack provides an excellent foundation for your projects. This comprehensive guide walks you through each step of the installation process, ensuring you have a fully functional web server environment by the end.

Introduction

LEMP stands for Linux, Nginx (pronounced “Engine-X”), MariaDB, and PHP. Unlike the traditional LAMP stack which uses Apache, LEMP employs Nginx as the web server component, offering significant performance advantages for high-traffic websites. Nginx’s event-driven architecture handles concurrent connections more efficiently than Apache’s process-driven approach, making it particularly well-suited for serving static content and proxying requests to application servers.

Fedora 42, as the Linux distribution in our LEMP stack, provides a cutting-edge yet stable platform with excellent security features and regular updates. The combination of these four components creates a versatile environment capable of hosting everything from simple blogs to complex web applications.

System administrators and web developers will find this guide particularly useful, as it provides detailed instructions for setting up a complete web development environment. By the end of this tutorial, you’ll have a fully functional LEMP stack ready for deploying your web projects.

Prerequisites

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

  • A server or computer running Fedora 42 (minimal installation is sufficient)
  • At least 2GB RAM (4GB or more recommended for production environments)
  • Minimum 20GB disk space (more for production websites)
  • Root or sudo privileges on your Fedora system
  • Basic familiarity with Linux command line operations
  • Active internet connection for downloading packages
  • DNS properly configured for your server
  • Ports 80 (HTTP) and 443 (HTTPS) available for web traffic

If you’re upgrading an existing system, create comprehensive backups of your data before proceeding. The entire installation process typically takes 30-45 minutes, depending on your system’s performance and internet connection speed.

To verify your current Fedora version, run the following command:

cat /etc/fedora-release

This should display “Fedora release 42” if you’re on the correct version.

Understanding the LEMP Stack Components

Before diving into the installation, let’s understand what each component contributes to the stack:

Linux (Fedora 42) serves as the foundation of the stack. Fedora 42 provides a robust, security-focused operating system with the latest kernel features optimized for server operations. Its package management system makes software installation and updates straightforward, while the modern kernel offers excellent process scheduling and memory management capabilities essential for web serving.

Nginx functions as the web server, handling HTTP requests and serving static content. Unlike Apache, Nginx uses an asynchronous, event-driven architecture that excels at managing multiple concurrent connections with minimal resource usage. This makes it particularly efficient for high-traffic websites and applications. Nginx also performs exceptionally well as a reverse proxy and load balancer.

MariaDB is a community-developed fork of MySQL that provides the database functionality in our stack. It offers improved performance, additional storage engines, and enhanced security features compared to MySQL. MariaDB maintains compatibility with MySQL while introducing new features and optimizations, making it an excellent choice for web applications that require reliable data storage.

PHP (with PHP-FPM) provides the programming language and processing capability for dynamic content. PHP-FPM (FastCGI Process Manager) is a significant improvement over traditional PHP processing methods, offering better resource management and performance. It allows for advanced features like process control, different user/group execution, and dynamic resource allocation.

Together, these components create a powerful ecosystem for web application deployment. The LEMP stack excels in scenarios requiring high performance, scalability, and efficient resource utilization, such as content management systems, e-commerce platforms, and custom web applications.

System Preparation

Proper system preparation ensures a smooth installation process and optimal performance of your LEMP stack. Follow these steps to prepare your Fedora 42 system:

First, update your package repository information to ensure you have access to the latest software versions:

sudo dnf clean all
sudo dnf check-update

Next, perform a full system upgrade to bring all packages to their latest versions:

sudo dnf upgrade -y

Setting a proper hostname helps with system identification and network configuration. Configure your hostname with:

sudo hostnamectl set-hostname your-server-name

Verify your network connectivity to ensure package downloads will work correctly:

ping -c 3 google.com

Check available disk space to confirm you have sufficient storage for the installation:

df -h

Install essential development tools and utilities that will be needed during the installation process:

sudo dnf groupinstall "Development Tools" -y
sudo dnf install wget curl vim -y

Finally, ensure your system time is synchronized correctly, which is crucial for proper logging and certificate validation:

sudo dnf install chrony -y
sudo systemctl enable chronyd
sudo systemctl start chronyd
sudo chronyc tracking

With these preparations complete, your Fedora 42 system is now ready for the LEMP stack installation.

Step 1: Installing Nginx Web Server

Nginx (pronounced “Engine-X”) will serve as our web server, handling HTTP requests and serving web content. Its lightweight, high-performance design makes it an excellent choice for web applications.

Begin by installing Nginx using the DNF package manager:

sudo dnf install nginx -y

This command installs the main Nginx package along with its dependencies. After installation completes, start the Nginx service and enable it to launch automatically at system boot:

sudo systemctl start nginx
sudo systemctl enable nginx

Verify that Nginx is running correctly with:

sudo systemctl status nginx

You should see output indicating that the service is active and running. Now check that Nginx is working by accessing your server’s IP address in a web browser. You should see the default Nginx welcome page.

If you don’t know your server’s IP address, you can find it with:

ip addr show

The main Nginx configuration files are located in various directories:

  • Main configuration: /etc/nginx/nginx.conf
  • Server blocks: /etc/nginx/conf.d/ directory
  • Default web content: /usr/share/nginx/html/
  • Log files: /var/log/nginx/

To verify the installed Nginx version and compiled modules:

nginx -v
nginx -V

If Nginx fails to start, check for common issues:

  • Port conflicts (something else using port 80)
  • Configuration syntax errors
  • Insufficient permissions

You can test your Nginx configuration file for syntax errors with:

sudo nginx -t

Step 2: Configuring Firewall Settings

Fedora 42 comes with firewalld as its default firewall management tool. For your LEMP stack to function properly, you need to configure the firewall to allow HTTP and HTTPS traffic.

First, check the current status of the firewall:

sudo firewall-cmd --state

If the firewall is running, open the necessary ports for web traffic. Add rules to allow HTTP (port 80) and HTTPS (port 443) connections:

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https

The --permanent flag ensures these changes persist after a system reboot. To make these rules take effect immediately, reload the firewall configuration:

sudo firewall-cmd --reload

Verify that the firewall rules have been correctly applied:

sudo firewall-cmd --list-all

You should see both http and https listed under the services section of the output.

To test remote access to your web server, try accessing your server’s IP address from another device. If the Nginx welcome page displays, your firewall is correctly configured.

For additional security, consider implementing rate limiting to protect against brute force attacks:

sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j REJECT
sudo firewall-cmd --reload

This rule limits the number of connections from a single IP address, helping to prevent denial-of-service attacks.

Step 3: Installing MariaDB Database Server

MariaDB provides the database functionality for our LEMP stack. It’s a powerful, open-source database server that’s compatible with MySQL but offers additional features and improvements.

Install MariaDB server packages using DNF:

sudo dnf install mariadb-server mariadb -y

Once installation completes, start the MariaDB service and enable it to launch at system boot:

sudo systemctl start mariadb
sudo systemctl enable mariadb

Verify that MariaDB is running correctly:

sudo systemctl status mariadb

For security purposes, run the mysql_secure_installation script to secure your database server:

sudo mysql_secure_installation

This interactive script will guide you through several security-related settings:

  • Setting a root password (if not already set)
  • Removing anonymous users
  • Disallowing root login remotely
  • Removing the test database
  • Reloading privilege tables

For each prompt, it’s generally recommended to answer “Y” (yes) to implement these security measures.

Now create your first database and user with appropriate permissions:

sudo mysql -u root -p

After entering the root password, you’ll be at the MariaDB command prompt. Create a database and user:

CREATE DATABASE mywebsite;
CREATE USER 'webuser'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON mywebsite.* TO 'webuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Replace ‘mywebsite‘, ‘webuser‘, and ‘secure_password‘ with your preferred values.

The main MariaDB configuration files are located at:

  • Main configuration: /etc/my.cnf
  • Additional configurations: /etc/my.cnf.d/ directory
  • Data directory: /var/lib/mysql/

For production environments, consider additional optimizations such as:

  • Adjusting the InnoDB buffer pool size
  • Configuring query cache settings
  • Setting appropriate maximum connections

Step 4: Installing PHP and PHP-FPM

PHP provides the capability to process dynamic content and interact with your database. For Nginx, we’ll use PHP-FPM (FastCGI Process Manager) which provides superior performance compared to traditional PHP processing methods.

Install PHP and necessary extensions using DNF:

sudo dnf install php php-fpm php-mysqlnd php-opcache php-gd php-xml php-mbstring php-json php-cli php-pear php-pdo php-zip php-intl php-common -y

This command installs PHP along with commonly needed extensions for web development. Fedora 42 typically includes recent PHP versions with the latest features and security updates.

After installation, start and enable the PHP-FPM service:

sudo systemctl start php-fpm
sudo systemctl enable php-fpm

Verify that PHP-FPM is running:

sudo systemctl status php-fpm

PHP-FPM uses pools to manage its processes. The default pool configuration is located at /etc/php-fpm.d/www.conf. This file contains settings for how PHP-FPM handles connections, processes, and resources.

To verify your PHP installation from the command line:

php -v

This displays the installed PHP version.

If you encounter issues with PHP-FPM:

  • Check log files at /var/log/php-fpm/
  • Verify socket permissions
  • Ensure the PHP-FPM service is running
  • Check for configuration syntax errors

Step 5: Configuring PHP for Security and Performance

Proper PHP configuration enhances both security and performance of your web applications. Edit the main PHP configuration file:

sudo nano /etc/php.ini

Make the following important security adjustments:

; Set for security
cgi.fix_pathinfo=0

; Memory limits
memory_limit = 256M

; Maximum execution time
max_execution_time = 60

; File upload settings
upload_max_filesize = 20M
post_max_size = 20M

; Error reporting (for production)
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

The cgi.fix_pathinfo=0 setting is particularly important for security when using PHP with Nginx, as it prevents PHP from executing code in partially matched file paths.

For security purposes, disable potentially dangerous PHP functions:

disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

After making these changes, restart PHP-FPM to apply them:

sudo systemctl restart php-fpm

To verify your PHP configuration changes, create a phpinfo file that will display all current settings:

echo "" | sudo tee /usr/share/nginx/html/info.php

Access this file through your web browser at http://your_server_ip/info.php. After verifying the settings, remove this file for security:

sudo rm /usr/share/nginx/html/info.php

Step 6: Integrating Nginx with PHP-FPM

To make Nginx work with PHP, you need to configure it to pass PHP requests to the PHP-FPM service. Edit the default Nginx server block:

sudo nano /etc/nginx/conf.d/default.conf

If this file doesn’t exist, create it. Add the following configuration:

server {
    listen 80;
    server_name your_domain.com www.your_domain.com;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

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

Replace your_domain.com with your actual domain name or server IP address.

The fastcgi_pass directive specifies how Nginx communicates with PHP-FPM. By default, PHP-FPM listens on a Unix socket at /var/run/php-fpm/www.sock. If you’ve configured PHP-FPM to use TCP instead, you would use fastcgi_pass 127.0.0.1:9000;.

Check your Nginx configuration for syntax errors:

sudo nginx -t

If the test is successful, restart Nginx to apply the changes:

sudo systemctl restart nginx

Make sure the web server user (nginx) has appropriate permissions to access the web root directory:

sudo chown -R nginx:nginx /usr/share/nginx/html

Common integration issues include:

  • Incorrect socket path in the Nginx configuration
  • Permission issues with the PHP-FPM socket
  • Misconfigured fastcgi parameters
  • SELinux restrictions

Step 7: Testing Your LEMP Installation

Testing is crucial to verify that all components of your LEMP stack are working together correctly. Create a test PHP file that will check both PHP processing and database connectivity:

sudo nano /usr/share/nginx/html/test.php

Add the following content:

<?php
echo "<h1>PHP is working!</h1>";

// Database connection test
$host = 'localhost';
$user = 'webuser';
$pass = 'secure_password';
$db = 'mywebsite';

try {
    $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<h2>Database connection successful!</h2>";
} catch(PDOException $e) {
    echo "<h2>Database connection failed: " . $e->getMessage() . "</h2>";
}

// Display PHP information
phpinfo();
?>

Replace the database credentials with those you created earlier.

Access this file in your web browser at http://your_server_ip/test.php. You should see confirmation that PHP is working and that the database connection is successful, followed by detailed PHP configuration information.

Check file permissions if you encounter access issues:

sudo chmod 644 /usr/share/nginx/html/test.php

After confirming everything works, remove the test file for security:

sudo rm /usr/share/nginx/html/test.php

Step 8: Setting Up Virtual Hosts

Virtual hosts allow you to host multiple websites on a single server. This is how you can set them up:

First, create directories for your website:

sudo mkdir -p /var/www/example.com/html
sudo mkdir -p /var/www/example.com/logs

Set appropriate ownership and permissions:

sudo chown -R nginx:nginx /var/www/example.com
sudo chmod -R 755 /var/www/example.com

Create a simple index.php file for testing:

echo '<?php echo "Welcome to example.com!"; ?>' | sudo tee /var/www/example.com/html/index.php

Create a new server block configuration:

sudo nano /etc/nginx/conf.d/example.com.conf

Add the following configuration:

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.php index.html index.htm;
    access_log /var/www/example.com/logs/access.log;
    error_log /var/www/example.com/logs/error.log;

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

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

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

Check your configuration for syntax errors:

sudo nginx -t

If the test passes, reload Nginx:

sudo systemctl reload nginx

For testing purposes, add your domain to your local hosts file:

sudo nano /etc/hosts

Add the following line:

127.0.0.1 example.com www.example.com

Now you can test your virtual host by accessing http://example.com in your browser.

Step 9: Performance Optimization

Optimize your LEMP stack for better performance with these adjustments:

Nginx Optimization:

Edit the Nginx configuration:

sudo nano /etc/nginx/nginx.conf

Adjust these settings based on your server’s resources:

worker_processes auto;
worker_connections 1024;
keepalive_timeout 65;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
client_max_body_size 20m;

PHP-FPM Optimization:

Edit the PHP-FPM pool configuration:

sudo nano /etc/php-fpm.d/www.conf

Adjust these settings based on your needs:

pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500

MariaDB Optimization:

Edit the MariaDB configuration:

sudo nano /etc/my.cnf.d/server.cnf

Add these settings under the [mysqld] section:

innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
query_cache_size = 32M
query_cache_limit = 2M
key_buffer_size = 32M

Enable PHP OpCache by editing:

sudo nano /etc/php.d/10-opcache.ini

Adjust these 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

After making these changes, restart all services:

sudo systemctl restart nginx
sudo systemctl restart php-fpm
sudo systemctl restart mariadb

Monitor resource usage with tools like:

sudo dnf install htop iotop -y

Step 10: Securing Your LEMP Stack

Implement these security measures to protect your web server:

Set Up SSL/TLS with Let’s Encrypt:

sudo dnf install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Configure Secure Headers in Nginx:

Add these to your server block:

add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self';";

Harden PHP Security:

Edit the PHP configuration:

sudo nano /etc/php.ini

Add/modify these settings:

expose_php = Off
session.cookie_httponly = 1
session.cookie_secure = 1

Secure MariaDB:

Run MySQL secure installation if you haven’t already:

sudo mysql_secure_installation

Set Up Regular Updates:

Create a cron job for regular updates:

sudo crontab -e

Add:

0 3 * * 0 dnf -y update >> /var/log/weekly_update.log 2>&1

Implement Regular Backups:

Use tools like mysqldump for database backups:

mysqldump -u root -p --all-databases > all_databases.sql

Troubleshooting Common Issues

Nginx Won’t Start:

  • Check logs: sudo journalctl -u nginx
  • Verify configuration: sudo nginx -t
  • Check for port conflicts: sudo ss -tulpn | grep :80

PHP-FPM Socket Connection Problems:

  • Verify socket exists: ls -la /var/run/php-fpm/
  • Check permissions: sudo chmod 666 /var/run/php-fpm/www.sock
  • Check PHP-FPM is running: sudo systemctl status php-fpm

MariaDB Access Denied Errors:

  • Reset root password if necessary
  • Verify user permissions: SHOW GRANTS FOR 'user'@'localhost';
  • Check hostname resolution issues

502 Bad Gateway Errors:

  • Verify PHP-FPM is running
  • Check Nginx error logs: sudo tail -f /var/log/nginx/error.log
  • Examine PHP-FPM logs: sudo tail -f /var/log/php-fpm/www-error.log

Permission Issues:

  • Set correct ownership: sudo chown -R nginx:nginx /path/to/webroot
  • Set proper permissions: sudo chmod -R 755 /path/to/webroot
  • Check SELinux contexts: sudo restorecon -Rv /path/to/webroot

Finding solutions to these common issues will help you maintain a stable and reliable LEMP stack environment on your Fedora 42 system.

Congratulations! You have successfully installed LEMP. Thanks for using this tutorial for installing the LEMP Stack on Fedora 42 Linux system. For additional help or useful information, we recommend you check the Fedora website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button