AlmaLinuxRHEL Based

How To Install LAMP Stack on AlmaLinux 10

Install LAMP Stack on AlmaLinux 10

In this tutorial, we will show you how to install LAMP Stack on AlmaLinux 10. Setting up a robust web hosting environment requires the right foundation. The LAMP stack—comprising Linux, Apache, MariaDB (or MySQL), and PHP—represents one of the most trusted and widely-deployed web server configurations in the industry. This powerful combination enables developers and system administrators to host dynamic websites, web applications, and content management systems with exceptional reliability and performance.

AlmaLinux 10, the latest enterprise-grade Linux distribution, provides an ideal platform for LAMP stack deployment. As a community-driven, open-source alternative to CentOS, AlmaLinux offers long-term stability, robust security features, and extensive package repositories that make it perfect for production web hosting environments.

This comprehensive guide walks you through every step of installing and configuring a complete LAMP stack on AlmaLinux 10. Whether you’re a beginner system administrator or an experienced developer, you’ll learn how to build a professional-grade web server from the ground up, complete with security hardening, performance optimization, and troubleshooting techniques.

Prerequisites and System Preparation

System Requirements

Before beginning the LAMP stack installation process, ensure your AlmaLinux 10 system meets the minimum requirements for optimal performance. A dedicated server or VPS with at least 1GB of RAM and 20GB of available disk space provides sufficient resources for most web applications. However, production environments typically benefit from 2GB or more RAM and additional storage capacity.

Your system must have root access or a user account with sudo privileges to execute administrative commands. Additionally, ensure your server maintains a stable internet connection throughout the installation process, as you’ll be downloading packages from various repositories.

Initial System Setup

Start by updating your AlmaLinux 10 system to ensure all packages are current and security patches are applied:

sudo dnf update -y
sudo dnf install epel-release -y

The Extra Packages for Enterprise Linux (EPEL) repository provides additional software packages that may be required during the LAMP stack configuration. Installing EPEL early in the process prevents potential dependency issues later.

If you plan to host websites with domain names, configure your DNS settings to point your domain’s A record to your server’s IP address. This step, while optional for testing purposes, is essential for production deployments.

Firewall and SELinux Considerations

AlmaLinux 10 ships with firewalld and SELinux enabled by default for enhanced security. While these features provide excellent protection, they require proper configuration to allow web traffic. You’ll configure these security components as part of the Apache installation process to ensure your web server remains both accessible and secure.

Installing and Configuring Apache Web Server

Apache Installation Process

Apache HTTP Server, known as httpd on Red Hat-based systems, serves as the foundation of your LAMP stack. Install Apache using the DNF package manager:

sudo dnf install httpd -y

This command downloads and installs Apache along with its dependencies from the official AlmaLinux repositories. The installation process typically completes within a few minutes, depending on your internet connection speed.

Service Management and Auto-Start Configuration

After installation, enable Apache to start automatically at boot and launch the service:

sudo systemctl enable httpd
sudo systemctl start httpd

Verify that Apache is running correctly by checking its status:

sudo systemctl status httpd

A successful installation displays an “active (running)” status with green indicators. If Apache fails to start, the status command provides error messages to help diagnose configuration issues.

Firewall Configuration for Web Traffic

Configure firewalld to allow HTTP and HTTPS traffic through your server’s firewall:

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

These commands permanently allow web traffic on ports 80 (HTTP) and 443 (HTTPS), ensuring your websites remain accessible to visitors. The reload command applies the changes immediately without requiring a system restart.

Apache Configuration and Testing

Test your Apache installation by navigating to your server’s IP address in a web browser. You should see the default Apache test page, confirming that the web server is functioning correctly. The default document root is located at /var/www/html/, where you can place your website files.

For custom configurations, Apache’s main configuration file resides at /etc/httpd/conf/httpd.conf. However, it’s recommended to create separate configuration files in /etc/httpd/conf.d/ for virtual hosts and custom settings to maintain better organization and easier management.

Installing and Securing MariaDB Database

MariaDB Installation and Setup

MariaDB, a robust open-source fork of MySQL, provides reliable database functionality for your web applications. Install MariaDB server and client packages:

sudo dnf install mariadb-server mariadb -y

The installation includes both the database server and command-line client tools necessary for database management and maintenance operations.

Database Service Configuration

Enable and start the MariaDB service to ensure it launches automatically at system boot:

sudo systemctl enable mariadb
sudo systemctl start mariadb

Confirm MariaDB is running properly:

sudo systemctl status mariadb

A properly functioning MariaDB service shows an “active (running)” status, indicating the database server is ready to accept connections.

Security Hardening with mysql_secure_installation

MariaDB ships with default settings designed for development convenience rather than production security. Run the security script to harden your database installation:

sudo mysql_secure_installation

This interactive script guides you through several security configurations:

  • Root Password: Set a strong password for the database root user
  • Anonymous Users: Remove anonymous user accounts that pose security risks
  • Remote Root Access: Disable remote root login to prevent unauthorized access
  • Test Database: Remove the default test database and associated privileges
  • Privilege Tables: Reload privilege tables to apply all changes immediately

Answer “Y” (yes) to all prompts except for switching to unix_socket authentication if you prefer password-based authentication for the root user.

Database Verification and Basic Operations

Test your MariaDB installation by connecting to the database server:

mysql -u root -p

Enter the root password you set during the security installation. Once connected, you can view existing databases and perform basic administrative tasks:

SHOW DATABASES;
SELECT VERSION();
EXIT;

These commands display available databases and confirm your MariaDB version, verifying that the database server is functioning correctly.

Installing and Configuring PHP

PHP 8.4 Installation with Essential Extensions

PHP serves as the server-side scripting language that processes dynamic content and connects to your database. Install PHP along with commonly required extensions:

sudo dnf install php php-mysqlnd php-opcache php-gd php-xml php-mbstring php-cli php-curl php-zip php-json -y

This comprehensive package selection includes:

  • php-mysqlnd: Native MySQL driver for database connectivity
  • php-opcache: Bytecode caching for improved performance
  • php-gd: Graphics library for image manipulation
  • php-xml: XML processing capabilities
  • php-mbstring: Multi-byte string handling for international content
  • php-cli: Command-line interface for PHP scripts
  • php-curl: HTTP client library for external API communications
  • php-zip: Archive manipulation functionality
  • php-json: JSON data processing support

PHP-FPM Configuration

While Apache can process PHP using mod_php, PHP-FPM (FastCGI Process Manager) offers better performance and resource management for production environments. Install and configure PHP-FPM:

sudo dnf install php-fpm -y
sudo systemctl enable php-fpm
sudo systemctl start php-fpm

Verify PHP-FPM is running:

sudo systemctl status php-fpm

Apache-PHP Integration

Restart Apache to enable PHP processing capabilities:

sudo systemctl restart httpd

Create a PHP test file to verify the integration:

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

Access http://your-server-ip/info.php in your web browser. A successful installation displays a comprehensive PHP information page showing your PHP version, loaded extensions, and configuration details.

Security Note: Remove the info.php file after testing, as it exposes sensitive server information:

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

Component Integration and Testing

Creating a Database Connection Test

Verify that all LAMP stack components work together by creating a simple PHP script that connects to MariaDB. First, create a test database and user:

mysql -u root -p

Execute the following SQL commands:

CREATE DATABASE lamptest;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'SecurePassword123!';
GRANT ALL PRIVILEGES ON lamptest.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Create a PHP script to test database connectivity:

sudo tee /var/www/html/dbtest.php > /dev/null << 'EOF'
<?php
$servername = "localhost";
$username = "testuser";
$password = "SecurePassword123!";
$database = "lamptest";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<h2>Database Connection Successful!</h2>";
    echo "<p>LAMP Stack is working correctly.</p>";
    
    // Display server information
    echo "<h3>Server Information:</h3>";
    echo "<p>PHP Version: " . phpversion() . "</p>";
    echo "<p>Database: " . $pdo->getAttribute(PDO::ATTR_SERVER_VERSION) . "</p>";
    
} catch(PDOException $e) {
    echo "<h2>Connection failed:</h2>";
    echo "<p>" . $e->getMessage() . "</p>";
}
?>
EOF

Access http://your-server-ip/dbtest.php to verify successful database connectivity. Remove this test file after verification for security reasons.

Virtual Host Configuration

Configure Apache virtual hosts to host multiple websites or properly organize your web applications:

sudo tee /etc/httpd/conf.d/yourdomain.com.conf > /dev/null << 'EOF'
<VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    DocumentRoot /var/www/yourdomain.com/public_html
    ErrorLog /var/log/httpd/yourdomain.com_error.log
    CustomLog /var/log/httpd/yourdomain.com_access.log combined
    
    <Directory "/var/www/yourdomain.com/public_html">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
EOF

Create the document root directory and set appropriate permissions:

sudo mkdir -p /var/www/yourdomain.com/public_html
sudo chown -R apache:apache /var/www/yourdomain.com
sudo chmod -R 755 /var/www/yourdomain.com

Security Hardening and Best Practices

Apache Security Configuration

Enhance Apache security by hiding version information and configuring security headers. Edit the main Apache configuration:

sudo tee -a /etc/httpd/conf.d/security.conf > /dev/null << 'EOF'
# Hide Apache version
ServerTokens Prod
ServerSignature Off

# Security 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"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
EOF

PHP Security Hardening

Configure PHP security settings by editing /etc/php.ini:

sudo cp /etc/php.ini /etc/php.ini.backup
sudo sed -i 's/expose_php = On/expose_php = Off/' /etc/php.ini
sudo sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/' /etc/php.ini
sudo sed -i 's/allow_url_fopen = On/allow_url_fopen = Off/' /etc/php.ini
sudo sed -i 's/allow_url_include = On/allow_url_include = Off/' /etc/php.ini

MariaDB Security Best Practices

Create application-specific database users instead of using the root account for web applications. Limit user privileges to only necessary databases and operations:

CREATE USER 'webappuser'@'localhost' IDENTIFIED BY 'StrongPassword123!';
GRANT SELECT, INSERT, UPDATE, DELETE ON webapp_db.* TO 'webappuser'@'localhost';

Configure MariaDB to bind only to localhost unless remote access is specifically required:

sudo tee -a /etc/my.cnf.d/security.cnf > /dev/null << 'EOF'
[mysqld]
bind-address = 127.0.0.1
EOF

Performance Optimization

Apache Performance Tuning

Optimize Apache’s Multi-Processing Module (MPM) configuration for better performance. Edit /etc/httpd/conf.modules.d/00-mpm.conf:

sudo tee /etc/httpd/conf.d/performance.conf > /dev/null << 'EOF'
# KeepAlive settings
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

# MPM Prefork settings (adjust based on available RAM)
<IfModule mpm_prefork_module>
    StartServers 8
    MinSpareServers 5
    MaxSpareServers 20
    ServerLimit 256
    MaxRequestWorkers 256
    MaxConnectionsPerChild 4000
</IfModule>
EOF

PHP Performance Optimization

Configure OPcache for improved PHP performance by editing /etc/php.d/10-opcache.ini:

sudo tee /etc/php.d/10-opcache.ini > /dev/null << 'EOF'
; Enable OPcache
opcache.enable=1
opcache.enable_cli=1

; Memory settings
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000

; Performance settings
opcache.revalidate_freq=2
opcache.fast_shutdown=1
EOF

MariaDB Performance Configuration

Optimize MariaDB settings in /etc/my.cnf.d/performance.cnf:

sudo tee /etc/my.cnf.d/performance.cnf > /dev/null << 'EOF'
[mysqld]
# InnoDB settings
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
innodb_flush_log_at_trx_commit = 2

# Query cache (for MariaDB < 10.3)
query_cache_type = 1
query_cache_size = 64M

# General performance
max_connections = 100
thread_cache_size = 16
table_open_cache = 2000
EOF

Troubleshooting Common Issues

Apache Troubleshooting

Service Won’t Start: Check Apache configuration syntax:

sudo httpd -t

Permission Denied Errors: Verify SELinux context:

sudo ls -Z /var/www/html/
sudo restorecon -Rv /var/www/

Port Already in Use: Check for conflicting services:

sudo netstat -tulpn | grep :80

PHP Issues

PHP Pages Display as Text: Ensure PHP module is loaded:

httpd -M | grep php

Extension Not Found: Install missing PHP extensions:

sudo dnf search php- | grep extension_name

File Upload Issues: Check PHP configuration:

php -i | grep -E "(upload_max_filesize|post_max_size|max_execution_time)"

Database Connection Problems

Access Denied Errors: Verify user privileges:

mysql -u username -p -e "SHOW GRANTS;"

Connection Refused: Check MariaDB service status:

sudo systemctl status mariadb
sudo journalctl -u mariadb

Socket Connection Issues: Verify socket file permissions:

ls -la /var/lib/mysql/mysql.sock

Maintenance and Monitoring

Regular Updates

Keep your LAMP stack components updated with security patches:

sudo dnf update httpd php* mariadb*
sudo systemctl restart httpd php-fpm mariadb

Log Monitoring

Monitor system logs for errors and security issues:

# Apache logs
sudo tail -f /var/log/httpd/error_log

# PHP-FPM logs
sudo tail -f /var/log/php-fpm/www-error.log

# MariaDB logs
sudo tail -f /var/log/mariadb/mariadb.log

Backup Strategies

Implement regular backup procedures for your databases and web content:

# Database backup
mysqldump -u root -p --all-databases > backup_$(date +%Y%m%d).sql

# Web files backup
tar -czf webfiles_$(date +%Y%m%d).tar.gz /var/www/

Congratulations! You have successfully installed LAMP. Thanks for using this tutorial for installing the LAMP Stack on AlmaLinux OS 10 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