How to Install LAMP Stack Setup On RHEL Rocky Ubuntu Alma Centos Linux: Step-by-Step Guide

Linux Administration / RHEL 9 / Apache / MariaDB / PHP

In this practical Linux administration tutorial, we will install and configure a complete LAMP Stack on Red Hat Enterprise Linux (RHEL) Rocky Ubuntu Alma Centos . You will learn how to configure Apache Web Server, MariaDB, PHP, PHP-FPM, firewall rules, and database connectivity.

This guide is designed for Linux System Administrators, RHCSA learners, and anyone who wants hands-on experience deploying a Linux-based web server.

LAMP Stack Architecture

Operating System: Red Hat Enterprise Linux 9

Web Server: Apache HTTP Server (httpd)

Database: MariaDB Server

Application Language: PHP

PHP Process Manager: PHP-FPM

HTTP Port: 80

HTTPS Port: 443, after TLS is configured

Web Root: /var/www/html


Section Number Section Topic
1 Prerequisites
2 Update RHEL 9
3 Install Apache
4 Configure the firewall
5 Test Apache
6 Install MariaDB
7 Secure MariaDB
8 Create a database and user
9 Install PHP and PHP-FPM
10 Test PHP
11 Create a PHP website
12 Connect PHP to MariaDB
13 Verify the installation
14 Troubleshooting
15 Security best practices
16 Conclusion

1. Prerequisites

Before starting, make sure you have:

  • A working RHEL 9 server or virtual machine.
  • A user account with sudo privileges.
  • Internet connectivity and access to the required software repositories.
  • A reachable server IP address.
  • At least 2 GB RAM recommended for a small practice lab.

2. Update RHEL 9

First, verify your operating system version and network configuration.

bash — system information
cat /etc/redhat-release
ip addr show
hostname -I
sudo dnf repolist

Update installed packages:

bash — system update
sudo dnf update -y

If DNF cannot find the required packages, check RHEL registration, repository availability, DNS resolution, and internet access.

3. Install Apache Web Server

Apache receives HTTP requests from browsers and serves website content. On RHEL, its service and package name is httpd.

bash — install Apache
sudo dnf install httpd -y
sudo systemctl enable --now httpd
sudo systemctl status httpd
sudo apachectl configtest
Expected result: The service should report active (running), and the configuration test should return Syntax OK.

Check whether Apache is listening on port 80:

bash — verify HTTP listener
sudo ss -lntp | grep ':80'

4. Configure the Firewall

RHEL uses firewalld to manage host firewall rules. Check its status first:

bash — firewall status
sudo systemctl status firewalld

If firewalld is running, allow HTTP traffic:

bash — allow HTTP and HTTPS
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
sudo firewall-cmd --list-services
Important: Adding the HTTPS firewall service does not configure HTTPS itself. You must also configure Apache TLS and a valid certificate. If your server is hosted in a cloud environment, check its security group or external firewall too.

5. Test Apache Web Server

Create a simple HTML page in the default web root:

bash — create test page
echo '<h1>Welcome to My RHEL LAMP Server</h1>' | sudo tee /var/www/html/index.html

Test the page locally:

bash — local HTTP test
curl http://localhost

Expected output:

output — HTML response
<h1>Welcome to My RHEL LAMP Server</h1>

Open http://YOUR_SERVER_IP in a browser and replace YOUR_SERVER_IP with your actual server IP address.

6. Install MariaDB Database Server

MariaDB is a relational database server used to store application data such as user accounts, website posts, and application records.

bash — install MariaDB
sudo dnf install mariadb-server -y
sudo systemctl enable --now mariadb
sudo systemctl status mariadb
mariadb --version

Check that the MariaDB service reports active (running).

7. Secure MariaDB

Run the security setup utility provided by your installed MariaDB package:

bash — database security setup
sudo mariadb-secure-installation

Follow the prompts appropriate to your installed version. Where applicable, remove anonymous accounts, restrict remote root login, and remove the test database.

Security note: MariaDB should not be exposed to the public internet for this lab. Keep database access local unless remote access is specifically required and secured.

8. Create a Database and Application User

Open the MariaDB console:

bash — database console
sudo mariadb

Create a database named lampdb:

sql — create database
CREATE DATABASE lampdb;

Create a dedicated application user. Replace the example password with a strong, unique password.

sql — create application user
CREATE USER 'lampuser'@'localhost'
IDENTIFIED BY 'ReplaceWithAStrongUniquePassword!';

Grant access only to the application database:

sql — grant database permissions
GRANT ALL PRIVILEGES ON lampdb.*
TO 'lampuser'@'localhost';

SHOW DATABASES;
EXIT;

The application account now has permissions on lampdb, rather than administrative access to every database.

9. Install PHP and PHP-FPM

PHP executes server-side application code. PHP-FPM manages PHP worker processes and communicates with Apache through FastCGI.

bash — install PHP packages
sudo dnf install php php-fpm php-mysqlnd -y
php -v
php -m

Enable and start PHP-FPM, then restart Apache:

bash — start PHP-FPM
sudo systemctl enable --now php-fpm
sudo systemctl restart httpd

sudo systemctl status php-fpm
sudo systemctl status httpd

RHEL package versions and enabled repositories can affect which PHP version is installed. Use the packages available from your configured repositories.

10. Test PHP Execution

Create a temporary PHP information page:

bash — create PHP test file
echo '<?php phpinfo(); ?>' | sudo tee /var/www/html/info.php

Visit http://YOUR_SERVER_IP/info.php. If the PHP information page appears, Apache is executing PHP successfully.

Critical: The PHP information page exposes environment details. Remove it immediately after testing.
bash — remove PHP test page
sudo rm -f /var/www/html/info.php

11. Create a PHP Website

Create the homepage:

bash — create homepage
sudo vi /var/www/html/index.php

Add the following code:

php — homepage
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RHEL LAMP Stack</title>
</head>
<body>
    <h1>Welcome to My LAMP Server</h1>
    <p>Apache and PHP are working on RHEL 9.</p>

    <?php
    echo "<p>Server time: " . date("Y-m-d H:i:s") . "</p>";
    ?>
</body>
</html>

Save the file and visit http://YOUR_SERVER_IP/index.php. You should see the welcome message and current server time.

12. Connect PHP to MariaDB

We will now test whether PHP can connect to the MariaDB database using PDO and the MySQL driver.

Open the homepage file again:

bash — edit PHP application
sudo vi /var/www/html/index.php

Replace its contents with this lab example. Enter the same database password you configured in Step 8.

php — database connectivity test
<?php
$host = "localhost";
$dbname = "lampdb";
$username = "lampuser";
$password = "ReplaceWithAStrongUniquePassword!";

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]
    );

    echo "<h1>LAMP Stack Installed Successfully!</h1>";
    echo "<p>Apache: Working</p>";
    echo "<p>PHP: Working</p>";
    echo "<p>MariaDB: Connected successfully</p>";

} catch (PDOException $e) {
    http_response_code(500);
    error_log($e->getMessage());
    echo "Database connection failed. Check the server logs.";
}
?>

Open http://YOUR_SERVER_IP/index.php in your browser.

Expected result
  • Apache: Working
  • PHP: Working
  • MariaDB: Connected successfully

If the connection fails, verify the database username, password, database name, and installed PHP MySQL driver.

Production security: This code is intended for a lab. Do not keep database credentials directly in a web-accessible script. Store secrets in a protected configuration file or an appropriate secrets-management system, and restrict access to that configuration.

13. Verify the Complete LAMP Stack

Check the status of all three primary services:

bash — service verification
systemctl is-active httpd
systemctl is-active php-fpm
systemctl is-active mariadb

Expected output:

output — service status
active
active
active

Check the installed packages:

bash — installed packages
rpm -q httpd mariadb-server php php-fpm php-mysqlnd

Check listening ports:

bash — network listeners
sudo ss -lntp

14. Common LAMP Stack Troubleshooting

ProblemCommand or action
Apache fails to startsudo journalctl -u httpd -n 50 --no-pager
Website is unreachablesudo firewall-cmd --list-services
Port 80 is not listeningsudo ss -lntp | grep ':80'
PHP is not executingCheck Apache PHP integration and PHP-FPM status.
MariaDB fails to startsudo journalctl -u mariadb -n 50 --no-pager
Database connection failsphp -m | grep -Ei 'PDO|mysql'
PHP-FPM errorssudo journalctl -u php-fpm -n 50 --no-pager

Check Apache's error log:

bash — Apache error log
sudo tail -n 50 /var/log/httpd/error_log

Check PHP-FPM logs:

bash — PHP-FPM logs
sudo journalctl -u php-fpm -n 50 --no-pager

Check MariaDB logs:

bash — MariaDB logs
sudo journalctl -u mariadb -n 50 --no-pager

If the issue persists, investigate SELinux audit messages, file contexts, DNS, routing, and any external firewall rules. Keep SELinux enabled rather than disabling it to bypass errors.

15. Security Best Practices

  • Keep RHEL and application packages updated.
  • Use HTTPS with a valid TLS certificate.
  • Keep MariaDB inaccessible from public networks unless remote access is required and properly secured.
  • Use dedicated database accounts with minimum necessary privileges.
  • Remove PHP test pages such as info.php.
  • Never publish database credentials in source code or Git repositories.
  • Keep SELinux enabled and investigate access denials correctly.
  • Back up website files and databases regularly.
  • Test restoration procedures, not just backup creation.
  • Review service logs and firewall rules periodically.

16. Conclusion

In this tutorial, we installed and configured a LAMP Stack on RHEL 9 using Apache, MariaDB, PHP, and PHP-FPM. We configured firewall rules, created a database and dedicated application user, tested PHP execution, and verified database connectivity.

This practical project helps Linux System Administrators develop real-world skills in web server administration, database management, service troubleshooting, and basic security hardening.

Practice these steps in a test environment before deploying a production website.


Production Linux Backups: Automating Directory & Database Backups with Tar, Rsync, and Cron

Data loss incidents caused by disk corruption, failed package upgrades, or human operational errors are inevitable if reliable recovery mechanisms are not configured. A solid infrastructure backup strategy adheres to the 3-2-1 principle: three copies of critical data, across two different storage media, with at least one offsite replica.

In this guide, we will design and deploy an automated, self-pruning backup engine on Linux using tar for directory archiving, mysqldump for database exports, rsync for remote replication over SSH, and cron for unattended scheduling.

architecture - backup workflow
Local Staging: /var/backups/system_backups/
Archive Types: Compressed tarball (.tar.gz) + Raw SQL dump (.sql.gz)
Retention Policy: Local 7-day prune | Remote perpetual sync
Transport Layer: Rsync over encrypted SSH tunnel (Port 22)
Execution Interval: Nightly at 02:00 AM UTC via Crontab

Step 1: Install Required Utilities & Create Directory Structure

Ensure standard archive, synchronization, and database client tools are installed on your production server:

bash - package setup
# Update package index and install tools
sudo apt update && sudo apt install -y rsync tar gzip cron mariadb-client

# Create a locked staging directory with strict permissions
sudo mkdir -p /var/backups/system_backups
sudo chmod 700 /var/backups/system_backups
sudo mkdir -p /opt/scripts

Step 2: Configure Passwordless SSH for Offsite Backups

If you plan to synchronize backups to an offsite cloud VPS, NAS, or storage box, configure an SSH key pair so rsync runs without user intervention:

bash - ssh key exchange
# Generate a dedicated ed25519 key without a passphrase
sudo ssh-keygen -t ed25519 -N "" -f /root/.ssh/backup_key

# Copy the public key to the remote storage host
sudo ssh-copy-id -i /root/.ssh/backup_key.pub backupuser@REMOTE_BACKUP_IP

# Verify passwordless login succeeds
sudo ssh -i /root/.ssh/backup_key backupuser@REMOTE_BACKUP_IP "echo 'SSH Connection Verified'"

Step 3: Build the Unified Backup Script

Create a robust, error-tolerant bash script at /opt/scripts/server_backup.sh:

bash - create script
sudo nano /opt/scripts/server_backup.sh

Paste the following production script:

bash - /opt/scripts/server_backup.sh
#!/usr/bin/env bash
set -Eeuo pipefail

# ==========================================
# CONFIGURATION VARIABLES
# ==========================================
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="/var/backups/system_backups"
LOG_FILE="/var/log/server_backup.log"
RETENTION_DAYS=7

# Source directories to protect
SOURCE_DIRS=(
    "/etc"
    "/var/www"
    "/home"
)

# Database credentials (use .my.cnf in production for safety)
DB_USER="root"
DB_PASS="YOUR_STRONG_DB_PASSWORD"
DB_NAME="production_db"

# Remote Storage Configuration (Leave blank if local-only)
REMOTE_SYNC_ENABLED=true
REMOTE_USER="backupuser"
REMOTE_HOST="REMOTE_BACKUP_IP"
REMOTE_DEST="/mnt/storage_pool/backups/"
SSH_KEY="/root/.ssh/backup_key"

# ==========================================
# EXECUTION LOGIC
# ==========================================
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log_message "=== BACKUP PROCESS STARTED ==="

# 1. ARCHIVE SYSTEM DIRECTORIES WITH TAR
for DIR in "${SOURCE_DIRS[@]}"; do
    if [ -d "$DIR" ]; then
        SAFE_NAME=$(echo "$DIR" | sed 's|^/||; s|/|_|g')
        ARCHIVE_FILE="${BACKUP_DIR}/${SAFE_NAME}_${TIMESTAMP}.tar.gz"
        log_message "Archiving directory: ${DIR} -> ${ARCHIVE_FILE}"
        tar -czpf "$ARCHIVE_FILE" -C / "$DIR" --exclude="*.log" --exclude="*.cache"
    else
        log_message "WARNING: Directory ${DIR} does not exist. Skipping."
    fi
done

# 2. DUMP MYSQL / MARIADB DATABASE
if command -v mysqldump &> /dev/null; then
    DB_ARCHIVE="${BACKUP_DIR}/db_${DB_NAME}_${TIMESTAMP}.sql.gz"
    log_message "Exporting database: ${DB_NAME} -> ${DB_ARCHIVE}"
    mysqldump -u"$DB_USER" -p"$DB_PASS" --single-transaction --quick "$DB_NAME" | gzip -9 > "$DB_ARCHIVE"
else
    log_message "INFO: mysqldump not found or omitted. Skipping database backup."
fi

# 3. ROTATE & DELETE LOCAL BACKUPS OLDER THAN RETENTION LIMIT
log_message "Purging local backups older than ${RETENTION_DAYS} days..."
find "$BACKUP_DIR" -type f \( -name "*.tar.gz" -o -name "*.sql.gz" \) -mtime +$RETENTION_DAYS -exec rm -f {} \;

# 4. OFFSITE REPLICATION VIA RSYNC OVER SSH
if [ "$REMOTE_SYNC_ENABLED" = true ]; then
    log_message "Initiating remote rsync replication to ${REMOTE_HOST}..."
    rsync -avz --delete -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=accept-new" \
        "$BACKUP_DIR/" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DEST}"
    log_message "Remote sync complete."
fi

log_message "=== BACKUP PROCESS COMPLETED SUCCESSFULLY ==="
exit 0

Step 4: Lock Down Permissions & Perform a Manual Dry Run

Because the script handles sensitive database credentials and root-owned files, lock its read and write permissions to the root user only:

bash - execute permissions
# Set executable bit and restrict access
sudo chmod 700 /opt/scripts/server_backup.sh
sudo chown root:root /opt/scripts/server_backup.sh

# Run manual test execution
sudo /opt/scripts/server_backup.sh

# Verify output in staging directory and review generated logs
ls -lh /var/backups/system_backups
cat /var/log/server_backup.log

Step 5: Schedule Automated Execution via Cron

Automate execution every night at 2:00 AM UTC by adding an entry to root's crontab:

bash - crontab configuration
# Open root crontab editor
sudo crontab -e

Append the schedule rule to the bottom of the crontab:

cron - nightly schedule
# Run system and database backup every night at 02:00 AM UTC
0 2 * * * /opt/scripts/server_backup.sh > /dev/null 2>&1

Verification & Restoration Drills

An untested backup cannot be considered a valid backup. Regularly run test restorations in an isolated sandbox directory:

bash - restore testing
# Verify tarball integrity without extracting
tar -tzf /var/backups/system_backups/etc_*.tar.gz > /dev/null && echo "Tar archive is valid"

# Extract archive into a temporary test folder
mkdir -p /tmp/restore_test
tar -xzf /var/backups/system_backups/var_www_*.tar.gz -C /tmp/restore_test/

# Verify database dump extraction
gunzip < /var/backups/system_backups/db_*.sql.gz | head -n 25

Implementing this workflow ensures that in the event of hardware failure, misconfiguration, or ransomware compromise, your servers can be restored to a known good state in minutes.

AWS Architecture Guide: How to Build a Custom VPC with Public & Private Subnets and Launch EC2

Deploying production cloud workloads directly into the default AWS VPC is a common security pitfall. A resilient cloud infrastructure requires an isolated network environment with distinct public and private subnets, granular routing, and strict security groups. In this guide, we walk through building a production-ready Virtual Private Cloud (VPC) on AWS and deploying an EC2 instance from scratch.

architecture - network specifications
VPC CIDR: 10.0.0.0/16
Region: ap-south-1 (Mumbai)
Public Subnet: 10.0.1.0/24 (AZ: ap-south-1a) - Bastion / Web Server
Private Subnet: 10.0.2.0/24 (AZ: ap-south-1b) - Database / Internal Apps

Step 1: Create the Custom VPC

Log in to the AWS Management Console, navigate to the VPC Dashboard, and click Create VPC.

  • Select VPC only.
  • Name tag: gaganweb-prod-vpc
  • IPv4 CIDR block: 10.0.0.0/16
  • Leave tenancy as Default and click Create VPC.

Once created, select the VPC, click Actions → Edit VPC settings, and check both Enable DNS resolution and Enable DNS hostnames.

Step 2: Provision Public & Private Subnets

Navigate to Subnets → Create subnet, select gaganweb-prod-vpc, and configure:

  1. Public Subnet:
    • Subnet name: public-subnet-1a
    • Availability Zone: ap-south-1a
    • IPv4 subnet CIDR block: 10.0.1.0/24
  2. Private Subnet:
    • Subnet name: private-subnet-1b
    • Availability Zone: ap-south-1b
    • IPv4 subnet CIDR block: 10.0.2.0/24
Note: Select public-subnet-1a, click Actions → Edit subnet settings, and check Enable auto-assign public IPv4 address so instances in this subnet receive public IP assignments automatically.

Step 3: Attach an Internet Gateway (IGW) & Configure Routing

An isolated VPC has no default path to the global internet. We must attach an Internet Gateway:

  1. Go to Internet Gateways → Create internet gateway. Name it gaganweb-igw.
  2. Select the new gateway, click Actions → Attach to VPC, and choose gaganweb-prod-vpc.
  3. Go to Route Tables → Create route table:
    • Name: public-rt
    • VPC: gaganweb-prod-vpc
  4. Open public-rt, go to the Routes tab, and click Edit routes:
    • Add Route: Destination 0.0.0.0/0 → Target Internet Gateway (select gaganweb-igw).
  5. Go to the Subnet associations tab → Edit subnet associations → select public-subnet-1a and save.

Step 4: Configure the Security Group (Stateful Firewall)

Navigate to Security Groups → Create security group:

  • Security group name: web-server-sg
  • VPC: gaganweb-prod-vpc

Add the following Inbound rules:

Type Protocol Port Range Source
SSH TCP 22 Your_Public_IP/32
HTTP TCP 80 0.0.0.0/0
HTTPS TCP 443 0.0.0.0/0

Step 5: Launch & Verify Your EC2 Instance

Go to the EC2 Dashboard → Launch instances:

  1. Name: gaganweb-web-01
  2. AMI: Ubuntu Server 24.04 LTS (HVM), SSD Volume Type.
  3. Instance type: t2.micro or t3.micro (Free tier eligible).
  4. Key pair: Create or select an existing .pem key pair.
  5. Network settings (Click Edit):
    • VPC: gaganweb-prod-vpc
    • Subnet: public-subnet-1a
    • Auto-assign public IP: Enable
    • Select existing security group: web-server-sg
  6. Click Launch instance.

Step 6: Connect and Test from Linux CLI

Once the instance displays Running status with 2/2 checks passed, connect via terminal:

bash - local machine
# Set strict private key permissions
chmod 400 my-key.pem

# Connect to the instance via public IPv4
ssh -i "my-key.pem" ubuntu@YOUR_EC2_PUBLIC_IP

After logging into the instance, verify default routing and install a lightweight web service to verify external traffic flow:

bash - ec2 instance shell
# Verify default gateway points to VPC router (.1)
ip route show

# Update apt repositories and install Nginx
sudo apt update && sudo apt install -y nginx

# Confirm service is active and listening on port 80
sudo systemctl status nginx --no-pager
sudo ss -tulpn | grep :80

Open your browser and navigate to http://YOUR_EC2_PUBLIC_IP. You will see the standard Nginx welcome page, confirming your custom VPC routing, Internet Gateway, and security group rules are operating as intended.

Linux Network Diagnostic Troubleshooting: 5 Essential CLI Tools for SysAdmins

When services fail to communicate, resolving packet drops, routing loops, and port conflicts quickly is critical. Here are the core command-line tools every network and systems engineer relies on daily.

1. Inspect Active Sockets and Listening Ports (ss)

The modern replacement for netstat to verify running network daemons:

bash - socket statistics
# List all listening TCP/UDP ports with associated process names
sudo ss -tulpn

2. Trace Route and Latency with MTR

Combines ping and traceroute into a real-time responsive linux network diagnostic tool:

bash - routing diagnostic
# Install and run a 10-packet trace to a destination IP/domain
sudo apt install -y mtr-tiny
mtr -rw -c 10 1.1.1.1

3. Test End-to-End Port Reachability with Netcat

Check if a remote firewall or security group is dropping traffic without generating excessive logs:

bash - port connectivity
# Verify connection to remote IP on port 443 with a 3-second timeout
nc -zv -w 3 192.168.1.1 443

Essential Linux Server Hardening: The First 10 Minutes Setup Guide

Whenever you spin up a fresh virtual machine or cloud instance (Ubuntu/Debian), securing your server before exposing it to public network traffic is essential. Follow these foundational hardening steps.

Step 1: Create a Non-Root Sudo User

Running everyday administrative operations directly as the root user poses unnecessary risk. Create a dedicated administrative user:

bash - user setup
# Add new user (replace 'adminuser' with your desired username)
adduser adminuser

# Grant administrative privileges
usermod -aG sudo adminuser

Step 2: Enforce SSH Key Authentication & Disable Root Login

Brute-force attacks target port 22 continuously. Disable remote root login and password-based SSH access:

bash - ssh configuration
# Open SSH daemon configuration
sudo nano /etc/ssh/sshd_config

# Set or update these key directives:
# PermitRootLogin no
# PasswordAuthentication no

# Validate configuration syntax and restart service
sudo sshd -t && sudo systemctl restart ssh

Step 3: Configure UFW (Uncomplicated Firewall)

Block all incoming ports by default and permit only essential traffic:

bash - firewall rules
# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH and web traffic
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Enable and inspect firewall status
sudo ufw enable
sudo ufw status verbose