How to Set Up a Secure LAMP Stack on Ubuntu 22.04

0
39

Introduction

Setting up a secure LAMP (Linux, Apache, MySQL/MariaDB, PHP) stack is essential for hosting dynamic websites and web applications. In this guide, you’ll learn how to set up a secure LAMP stack on Ubuntu 22.04, with detailed steps, commands, and explanations to ensure optimal security and performance.

Prerequisites

Before we begin, make sure you have:

  • An Ubuntu 22.04 server
  • Root or sudo access

Step 1: Update System Packages

Keeping your system up-to-date is the first step in securing your server. Run the following command to update your packages:

sudo apt update && sudo apt upgrade -y

This ensures all security patches and updates are applied.

Step 2: Install Apache Web Server

Apache is a popular open-source web server. Install it with:

sudo apt install apache2 -y
sudo systemctl start apache2
sudo systemctl enable apache2

To verify that Apache is running:

sudo systemctl status apache2

You should see that the service is active and running.

Step 3: Secure Apache with UFW Firewall

Configure the UFW firewall to allow traffic on ports 80 (HTTP) and 443 (HTTPS):

sudo ufw allow ‘Apache Full’
sudo ufw enable
sudo ufw status

This ensures that only web traffic can reach your server, enhancing security.

Step 4: Install MySQL Database Server

Install MySQL, the database server for your LAMP stack:

sudo apt install mysql-server -y
sudo systemctl start mysql
sudo systemctl enable mysql

Secure your MySQL installation:

sudo mysql_secure_installation

Follow the prompts to set a root password, remove anonymous users, disable remote root login, and remove the test database.

Step 5: Install PHP

PHP is the scripting language that interacts with your database to generate dynamic content. Install PHP and the necessary modules:

sudo apt install php libapache2-mod-php php-mysql -y

Check your PHP version to confirm the installation:

php -v

Step 6: Configure Apache to Use PHP

Create a simple PHP file to test if PHP is working correctly with Apache:

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

Add the following code:

<?php phpinfo(); ?>

Save and exit the file, then restart Apache to apply the changes:

sudo systemctl restart apache2

Now, visit http://your_server_ip/info.php in your browser. If PHP is configured correctly, you’ll see the PHP info page. Remember to delete this file after testing:

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

Conclusion

Congratulations! You have successfully set up a secure LAMP stack on Ubuntu 22.04. Your server is now ready to host dynamic websites and web applications. For enhanced security, consider hardening your Apache and MySQL configurations, and regularly updating your system.