RHEL BasedRocky Linux

How To Install LAMP Stack on Rocky Linux 10

Install LAMP Stack on Rocky Linux 10

In this tutorial, we will show you how to install LAMP Stack on Rocky Linux 10. The LAMP stack remains the cornerstone of modern web development, powering millions of websites worldwide. When combined with Rocky Linux 10’s enterprise-grade stability, this powerful combination creates an ideal foundation for hosting dynamic web applications. Rocky Linux 10, as the spiritual successor to CentOS, offers the reliability and security that developers and system administrators demand.

Installing a LAMP stack on Rocky Linux 10 provides you with a robust web development environment consisting of Linux as the operating system, Apache as the web server, MySQL or MariaDB for database management, and PHP for server-side scripting. This comprehensive guide will walk you through every step of the installation process, from initial system preparation to performance optimization, ensuring you have a production-ready web server by the end.

Whether you’re a seasoned system administrator or a developer looking to set up your first web server, this tutorial provides detailed instructions, troubleshooting tips, and best practices. The entire installation process typically takes 30-45 minutes, depending on your system specifications and internet connection speed.

Understanding LAMP Stack Components

Linux Foundation: Rocky Linux 10

Rocky Linux 10 serves as the solid foundation for your LAMP stack installation. This enterprise-grade operating system provides long-term stability, security updates, and compatibility with Red Hat Enterprise Linux. The distribution includes modern package management tools and follows industry-standard security practices, making it an excellent choice for production environments.

Apache HTTP Server: The Web Gateway

Apache HTTP Server stands as the world’s most popular web server software, powering over 40% of all websites globally. Its modular architecture allows for extensive customization, while its proven track record ensures reliability under heavy loads. Apache’s virtual host capabilities enable hosting multiple websites on a single server, making it cost-effective for various deployment scenarios.

MySQL/MariaDB: Database Powerhouse

The database layer handles all data storage and retrieval operations for your web applications. MySQL continues to dominate the relational database market, while MariaDB offers enhanced features and improved performance as a drop-in replacement. Both databases provide ACID compliance, robust security features, and excellent scalability options.

PHP: Server-Side Scripting Engine

PHP powers dynamic web content generation, handling everything from simple contact forms to complex e-commerce platforms. The language’s extensive library ecosystem, combined with its seamless integration with Apache and MySQL, makes it the preferred choice for rapid web application development.

These four components work together seamlessly. Apache receives HTTP requests and determines whether to serve static content directly or pass dynamic requests to PHP, which can then interact with the database to generate customized responses.

Prerequisites and System Requirements

Hardware Requirements

Your Rocky Linux 10 server should meet minimum hardware specifications for optimal LAMP stack performance. Allocate at least 2GB of RAM for basic operations, though 4GB or more is recommended for production environments. Storage requirements vary based on your intended use, but start with at least 20GB of available disk space.

CPU requirements are generally modest for most web applications. A dual-core processor handles typical workloads efficiently, while more demanding applications benefit from additional cores and higher clock speeds.

Software Requirements

Begin with a fresh Rocky Linux 10 installation to avoid potential conflicts with existing software packages. Ensure your system has root access or a user account with sudo privileges for administrative tasks. A stable internet connection is essential for downloading packages and updates throughout the installation process.

Network Configuration Essentials

Configure your firewall to allow HTTP traffic on port 80 and HTTPS traffic on port 443. Database connections typically use port 3306, though this should remain restricted to localhost for security purposes. If you’re working on a remote server, ensure SSH access on port 22 remains available.

Preparing Rocky Linux 10 System

System Updates and Package Management

Start by updating your system packages to ensure you have the latest security patches and software versions:

sudo dnf update -y

This command updates all installed packages and their dependencies. The DNF package manager in Rocky Linux 10 provides improved dependency resolution and faster package operations compared to older package managers.

Install essential development tools and utilities that support LAMP stack operations:

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

These tools provide compilation capabilities, file download utilities, text editors, and system monitoring capabilities that prove invaluable during server administration.

System Configuration

Configure your system hostname to reflect its purpose:

sudo hostnamectl set-hostname lamp-server.example.com

Verify the hostname change:

hostnamectl status

Update your hosts file to include the new hostname:

echo "127.0.0.1 lamp-server.example.com" | sudo tee -a /etc/hosts

Installing and Configuring Apache Web Server

Apache Installation Process

Rocky Linux 10 uses the httpd package name for Apache web server. Install Apache using the DNF package manager:

sudo dnf install httpd -y

This command downloads and installs Apache HTTP Server along with its essential dependencies. The installation typically completes within 2-3 minutes, depending on your internet connection speed.

Start the Apache service and enable it to automatically start at boot time:

sudo systemctl start httpd
sudo systemctl enable httpd

Verify that Apache is running correctly:

sudo systemctl status httpd

The status command should display “active (running)” in green text, indicating successful service startup.

Firewall Configuration for Web Traffic

Rocky Linux 10 includes firewalld as the default firewall management tool. Configure it to allow HTTP and HTTPS traffic:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Verify the firewall rules are active:

sudo firewall-cmd --list-all

The output should include both “http” and “https” in the services section.

Apache Configuration and Virtual Hosts

Apache’s main configuration file resides at /etc/httpd/conf/httpd.conf. The default document root is /var/www/html, where you’ll place your web content.

Create a simple test page to verify Apache functionality:

echo "<h1>Apache on Rocky Linux 10 - LAMP Stack</h1>" | sudo tee /var/www/html/index.html

Set appropriate permissions for the web directory:

sudo chown -R apache:apache /var/www/html
sudo chmod -R 755 /var/www/html

Test your Apache installation by accessing your server’s IP address in a web browser. You should see your test page displaying the heading you created.

For multiple websites, configure virtual hosts by creating configuration files in /etc/httpd/conf.d/. Each virtual host allows you to serve different websites from the same server.

Installing and Securing MySQL/MariaDB Database

Choosing Your Database Management System

Rocky Linux 10 repositories include both MySQL and MariaDB options. MariaDB offers enhanced performance and additional features while maintaining full MySQL compatibility. For most applications, MariaDB provides superior performance and more active development.

MariaDB Installation and Configuration

Install MariaDB server and client packages:

sudo dnf install mariadb-server mariadb -y

Start and enable the MariaDB service:

sudo systemctl start mariadb
sudo systemctl enable mariadb

Verify MariaDB is running:

sudo systemctl status mariadb

Database Security Hardening

Run the security installation script to secure your MariaDB installation:

sudo mysql_secure_installation

This interactive script guides you through several security improvements:

  1. Set root password: Choose a strong password for the database administrator account
  2. Remove anonymous users: Delete default anonymous user accounts that pose security risks
  3. Disable remote root login: Prevent root database access from remote locations
  4. Remove test database: Delete the default test database that provides unnecessary access
  5. Reload privilege tables: Apply all security changes immediately

Answer “Y” to all prompts except for the root password change if you’re setting it for the first time.

Database User Management

Create a dedicated database user for your web applications instead of using the root account:

sudo mysql -u root -p

Within the MySQL/MariaDB prompt, execute these commands:

CREATE DATABASE webapp_db;
CREATE USER 'webapp_user'@'localhost' IDENTIFIED BY 'strong_password_here';
GRANT ALL PRIVILEGES ON webapp_db.* TO 'webapp_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

This creates a database named webapp_db and a user with full privileges on that specific database, following the principle of least privilege.

Installing and Configuring PHP

PHP Installation Options

Rocky Linux 10 includes PHP in its default repositories. Install PHP and essential modules for web development:

sudo dnf install php php-cli php-fpm php-mysqlnd php-zip php-devel php-gd php-mcrypt php-mbstring php-curl php-xml php-pear php-bcmath php-json -y

Each module serves specific purposes:

  • php-mysqlnd: Native MySQL driver for database connectivity
  • php-gd: Graphics library for image manipulation
  • php-mbstring: Multibyte string handling for international character sets
  • php-curl: Client URL library for HTTP requests
  • php-xml: XML parsing and generation capabilities
  • php-json: JSON data format handling

PHP Configuration Optimization

The main PHP configuration file is located at /etc/php.ini. Edit key settings for optimal performance and security:

sudo nano /etc/php.ini

Modify these important settings:

memory_limit = 256M
upload_max_filesize = 50M
post_max_size = 50M
max_execution_time = 300
date.timezone = "Asia/Jakarta"

These settings optimize PHP for typical web applications while providing reasonable security boundaries.

Apache-PHP Integration

Restart Apache to load the PHP modules:

sudo systemctl restart httpd

Create a PHP information page to verify the installation:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

Access http://your-server-ip/info.php in your browser to view detailed PHP configuration information. Remove this file after verification for security purposes:

sudo rm /var/www/html/info.php

Testing LAMP Stack Installation

Database Connectivity Testing

Create a comprehensive PHP script to test database connectivity:

sudo nano /var/www/html/db_test.php

Add this content:

<?php
$servername = "localhost";
$username = "webapp_user";
$password = "strong_password_here";
$dbname = "webapp_db";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Database connection successful!<br>";
    
    // Test table creation
    $sql = "CREATE TABLE IF NOT EXISTS test_table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )";
    $pdo->exec($sql);
    echo "Test table created successfully!<br>";
    
    // Insert test data
    $stmt = $pdo->prepare("INSERT INTO test_table (name) VALUES (?)");
    $stmt->execute(["LAMP Stack Test"]);
    echo "Test data inserted successfully!<br>";
    
    // Retrieve test data
    $stmt = $pdo->query("SELECT * FROM test_table");
    while ($row = $stmt->fetch()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Created: " . $row["created_at"] . "<br>";
    }
    
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Access this script through your browser to verify complete LAMP stack functionality. Remove the test file after successful verification.

Performance Verification

Monitor system resources during testing:

htop

Check Apache error logs for any issues:

sudo tail -f /var/log/httpd/error_log

Monitor MariaDB performance:

sudo mysqladmin -u root -p status

Security Hardening and Best Practices

Apache Security Configuration

Hide Apache version information by editing the configuration:

sudo nano /etc/httpd/conf/httpd.conf

Add these security directives:

ServerTokens Prod
ServerSignature Off

Configure security headers by creating a security configuration file:

sudo nano /etc/httpd/conf.d/security.conf

Add these headers:

Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

MySQL/MariaDB Security Enhancements

Configure MariaDB to bind only to localhost by editing the configuration file:

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

Add under the [mysqld] section:

bind-address = 127.0.0.1

Restart MariaDB to apply changes:

sudo systemctl restart mariadb

PHP Security Settings

Edit PHP configuration for enhanced security:

sudo nano /etc/php.ini

Modify these security-related settings:

expose_php = Off
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
allow_url_fopen = Off
allow_url_include = Off

These settings hide PHP version information, disable error display in production, and prevent remote file inclusion vulnerabilities.

Troubleshooting Common Issues

Apache Service Problems

If Apache fails to start, check the error logs:

sudo journalctl -u httpd -l

Common issues include configuration syntax errors or port conflicts. Verify configuration syntax:

sudo httpd -t

Database Connection Issues

For MySQL socket errors, verify the service is running:

sudo systemctl status mariadb

Check database logs for specific error messages:

sudo tail -f /var/log/mariadb/mariadb.log

PHP Module Loading Problems

Verify PHP modules are loaded correctly:

php -m

If modules are missing, reinstall them:

sudo dnf reinstall php-mysqlnd php-gd php-mbstring

Permission and Ownership Issues

Web content must have proper ownership and permissions:

sudo chown -R apache:apache /var/www/html
sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;

Performance Optimization and Monitoring

Apache Performance Tuning

Configure Apache for optimal performance by editing the main configuration:

sudo nano /etc/httpd/conf/httpd.conf

Adjust worker process settings based on your server resources:

<IfModule mpm_prefork_module>
    StartServers 8
    MinSpareServers 5
    MaxSpareServers 20
    ServerLimit 256
    MaxRequestWorkers 256
    MaxConnectionsPerChild 4000
</IfModule>

Enable compression to reduce bandwidth usage:

sudo nano /etc/httpd/conf.d/compression.conf

Add compression configuration:

LoadModule deflate_module modules/mod_deflate.so
<Location />
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI \
        \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
</Location>

Database Optimization

Configure basic MariaDB tuning by editing the configuration file:

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

Add performance settings under [mysqld]:

innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
query_cache_size = 64M
query_cache_type = 1
max_connections = 100

Monitoring and Maintenance

Set up log rotation to prevent disk space issues:

sudo nano /etc/logrotate.d/httpd

Monitor system performance regularly:

# Check disk usage
df -h

# Monitor memory usage
free -h

# Check active connections
ss -tuln

Next Steps and Advanced Configuration

SSL Certificate Installation

Secure your web server with SSL certificates using Let’s Encrypt:

sudo dnf install certbot python3-certbot-apache -y
sudo certbot --apache -d your-domain.com

Virtual Host Configuration

Create multiple website configurations:

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

Add virtual host configuration:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com
    ErrorLog /var/log/httpd/example.com_error.log
    CustomLog /var/log/httpd/example.com_access.log combined
</VirtualHost>

Backup and Maintenance Strategies

Implement automated backup scripts for database content:

#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
mysqldump -u root -p webapp_db > /backup/webapp_db_$DATE.sql

Schedule regular backups using cron:

sudo crontab -e

Add this line for daily backups at 2 AM:

0 2 * * * /path/to/backup-script.sh

Congratulations! You have successfully installed LAMP. Thanks for using this tutorial for installing the LAMP Stack on your Rocky Linux 10 system. For additional help or useful information, we recommend you check the official LAMP 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