How to Set Up a Linux Web Server with Apache, MySQL, and PHP (LAMP Stack)

Introduction

Setting up a LAMP stack (Linux, Apache, MySQL, PHP) is a fundamental skill for web developers and system administrators. This comprehensive tutorial will guide you through installing and configuring each component on Ubuntu 22.04 LTS, creating a robust foundation for hosting dynamic websites and web applications.

What is a LAMP Stack?

LAMP is an acronym representing four key components of a web development stack:

  • Linux: The operating system foundation
  • Apache: The web server software
  • MySQL: The database management system
  • PHP: The server-side scripting language

This combination provides everything needed to serve dynamic, database-driven websites efficiently and securely.

Prerequisites

  • Ubuntu 22.04 LTS server or desktop
  • Root or sudo access
  • Stable internet connection
  • Basic command-line knowledge
  • At least 2GB RAM and 20GB storage

Step 1: Update System Packages

Always start by updating your system to ensure you have the latest security patches:

sudo apt update && sudo apt upgrade -y

Step 2: Install Apache Web Server

Apache is one of the most popular web servers globally, known for its reliability and extensive documentation.

Installation

sudo apt install apache2 -y

Configure Firewall

# Enable UFW if not already enabled
sudo ufw enable

# Allow Apache through firewall
sudo ufw allow "Apache Full"

# Check firewall status
sudo ufw status

Start and Enable Apache

sudo systemctl start apache2
sudo systemctl enable apache2

Verify Installation

Open your web browser and navigate to your server’s IP address:

http://your_server_ip

You should see the Apache2 Ubuntu Default Page, confirming successful installation.

Step 3: Install MySQL Database Server

MySQL will store and manage your website’s data efficiently.

Installation

sudo apt install mysql-server -y

Secure MySQL Installation

Run the security script to improve MySQL’s security:

sudo mysql_secure_installation

Follow the prompts to:

  • Set up the validate password plugin (recommended)
  • Set a strong root password
  • Remove anonymous users
  • Disable remote root login
  • Remove test database
  • Reload privilege tables

Test MySQL Connection

sudo mysql -u root -p

Enter your root password when prompted. Exit MySQL with:

EXIT;

Step 4: Install PHP

PHP will process server-side scripts and generate dynamic content.

Install PHP and Common Modules

sudo apt install php libapache2-mod-php php-mysql php-cli php-curl php-json php-cgi php-gd php-mbstring php-xml php-xmlrpc php-zip -y

Configure Apache to Prioritize PHP Files

Edit the Apache directory index configuration:

sudo nano /etc/apache2/mods-enabled/dir.conf

Move index.php to the first position:

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

Restart Apache

sudo systemctl restart apache2

Step 5: Test PHP Processing

Create a PHP info file to verify PHP is working correctly:

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

Add the following content:

<?php
phpinfo();
?>

Visit http://your_server_ip/info.php in your browser. You should see a detailed PHP configuration page.

Security Note: Remove this file after testing:

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

Step 6: Create a MySQL Database and User

Set up a database for your web application:

sudo mysql -u root -p

Execute the following SQL commands:

# Create database
CREATE DATABASE sample_db;

# Create user with secure password
CREATE USER 'webapp_user'@'localhost' IDENTIFIED BY 'secure_password_123';

# Grant privileges
GRANT ALL PRIVILEGES ON sample_db.* TO 'webapp_user'@'localhost';

# Flush privileges
FLUSH PRIVILEGES;

# Exit MySQL
EXIT;

Step 7: Test Database Connection with PHP

Create a PHP script to test the database connection:

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

Add the following code:

<?php
$servername = "localhost";
$username = "webapp_user";
$password = "secure_password_123";
$dbname = "sample_db";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully to MySQL database!";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Visit http://your_server_ip/db_test.php to test the connection.

Security Note: Remove this file after testing:

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

Step 8: Configure Virtual Hosts

Set up virtual hosts to serve multiple websites from one server:

Create Directory Structure

sudo mkdir -p /var/www/your_domain/public_html
sudo chown -R $USER:$USER /var/www/your_domain/public_html
sudo chmod -R 755 /var/www/your_domain

Create Sample Index Page

nano /var/www/your_domain/public_html/index.html

Add sample content:

<html>
    <head>
        <title>Welcome to Your Domain!</title>
    </head>
    <body>
        <h1>Success! Your domain virtual host is working!</h1>
    </body>
</html>

Create Virtual Host Configuration

sudo nano /etc/apache2/sites-available/your_domain.conf

Add the following configuration:

<VirtualHost *:80>
    ServerAdmin webmaster@your_domain
    ServerName your_domain
    ServerAlias www.your_domain
    DocumentRoot /var/www/your_domain/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Enable the Virtual Host

sudo a2ensite your_domain.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2

Step 9: Security Hardening

Hide Apache Version

sudo nano /etc/apache2/conf-available/security.conf

Update these lines:

ServerTokens Prod
ServerSignature Off

Disable Unnecessary Modules

sudo a2dismod status
sudo a2dismod autoindex
sudo systemctl restart apache2

Configure PHP Security

sudo nano /etc/php/8.1/apache2/php.ini

Update these settings:

expose_php = Off
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
post_max_size = 8M
upload_max_filesize = 2M

Step 10: Install SSL Certificate

Secure your website with Let’s Encrypt SSL:

# Install Certbot
sudo apt install certbot python3-certbot-apache -y

# Obtain SSL certificate
sudo certbot --apache -d your_domain -d www.your_domain

# Test automatic renewal
sudo certbot renew --dry-run

Performance Optimization

Enable Apache Modules

sudo a2enmod rewrite
sudo a2enmod deflate
sudo a2enmod expires
sudo a2enmod headers
sudo systemctl restart apache2

Configure MySQL Performance

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Add under [mysqld] section:

innodb_buffer_pool_size = 128M
query_cache_type = 1
query_cache_size = 16M
query_cache_limit = 1M

Enable PHP OPcache

sudo nano /etc/php/8.1/apache2/php.ini

Add or update:

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=2

Monitoring and Maintenance

Log File Locations

  • Apache logs: /var/log/apache2/
  • MySQL logs: /var/log/mysql/
  • PHP logs: /var/log/php_errors.log

Regular Maintenance Tasks

# Check Apache status
sudo systemctl status apache2

# Check MySQL status
sudo systemctl status mysql

# View recent Apache errors
sudo tail -f /var/log/apache2/error.log

# Monitor disk usage
df -h

# Check memory usage
free -h

Troubleshooting Common Issues

Apache Won’t Start

# Check configuration syntax
sudo apache2ctl configtest

# Check detailed error logs
sudo journalctl -u apache2.service

PHP Scripts Not Executing

# Verify PHP module is enabled
sudo a2enmod php8.1

# Restart Apache
sudo systemctl restart apache2

Database Connection Issues

# Check MySQL service
sudo systemctl status mysql

# Test MySQL connection
mysql -u webapp_user -p sample_db

Next Steps

  1. Install phpMyAdmin for database management
  2. Set up automated backups
  3. Configure log rotation
  4. Implement monitoring solutions
  5. Deploy your web application

Conclusion

You now have a fully functional LAMP stack ready for hosting dynamic websites and web applications. This setup provides a solid foundation for web development projects, from simple websites to complex applications.

Remember to keep all components updated, monitor logs regularly, and follow security best practices to maintain a secure and efficient web server environment.

Add Comment