Deploying a LEMP Stack on AWS EC2: A Step-by-Step Guide

The LEMP stack is a popular group of open-source software that powers dynamic websites and web applications. It stands for Linux, Nginx (pronounced Engine-X), MySQL, and PHP. If you're familiar with the LAMP stack (which uses Apache instead of Nginx), LEMP is its cousin, designed for high-performance environments where you need efficient handling of concurrent connections.

In this blog post, I’ll walk you through setting up a LEMP stack on an AWS EC2 instance running Ubuntu 24.04 LTS. By the end, you will have a fully functioning web server with a MySQL database and PHP support.

Why Use the LEMP Stack?

The LEMP stack is chosen for a variety of reasons:

  • Nginx is highly performant and can handle more concurrent connections compared to Apache, making it an ideal choice for scaling web applications.

  • MySQL is a reliable and widely-used database management system, perfect for data-heavy applications.

  • PHP powers a large portion of dynamic websites and applications, from WordPress to custom apps.

In this guide, I’ll show you how to deploy a LEMP stack in just a few steps and explain the configuration needed for a smooth deployment.

Prerequisites

Before we start, here are a few things you’ll need:

  • An AWS account and basic familiarity with EC2.

  • A local machine with SSH or AWS CLI installed to connect to your EC2 instance.

  • An understanding of security group configurations to allow access to your web server.

Step 1: Launching an EC2 Instance

We begin by launching an EC2 instance on AWS. Here are the steps:

  1. Log in to your AWS Management Console.

  2. Navigate to the EC2 Dashboard and click on Launch Instance.

  3. Choose Ubuntu 24.04 LTS as your Amazon Machine Image (AMI).

  4. Select an instance type (t2.micro is great for free-tier users).

  5. Configure your instance, allowing HTTP (port 80) and SSH (port 22) in your Security Group settings.

  6. Launch the instance and download your .pem key for SSH access.

Once the instance is running, connect to it using SSH:

ssh -i "your-key.pem" ubuntu@<your-ec2-public-ip>

Step 2: Installing Nginx

With your EC2 instance ready, the first component to install is Nginx, which will serve as our web server.

Install Nginx:

sudo apt update
sudo apt install nginx

Check that Nginx is running correctly:

sudo systemctl status nginx

If you see a green active (running) status, Nginx has been successfully installed and started. You can verify it by opening your browser and navigating to the following address:

http://<ec2-instance-public-ip>

You should see the default Nginx Welcome Page.

Step 3: Installing MySQL

Next, let’s install MySQL to handle the database part of our stack.

Install MySQL:

sudo apt install mysql-server

After installation, secure your MySQL setup:

sudo mysql_secure_installation

This script helps improve security by allowing you to set a root password and configure other security settings.

Step 4: Installing PHP

While Nginx is great for serving static content, we need PHP to process dynamic content. Unlike Apache, which embeds the PHP interpreter into each request, Nginx relies on an external program called PHP-FPM (FastCGI Process Manager) to handle PHP processing.

Install PHP and PHP-FPM:

sudo apt install php-fpm php-mysql

PHP-FPM will act as a bridge between PHP and Nginx to process dynamic requests efficiently.

Step 5: Configuring Nginx for PHP Processing

At this stage, you have all the necessary software installed, but Nginx needs to be configured to process PHP files.

Create a Directory for Your Project:

sudo mkdir /var/www/projectLEMP
sudo chown -R $USER:$USER /var/www/projectLEMP

Configure Nginx to Serve Your PHP Website:

  1. Create a new Nginx configuration file:

     sudo nano /etc/nginx/sites-available/projectLEMP
    
  2. Add the following configuration:

     server {
         listen 80;
         server_name projectLEMP www.projectLEMP;
         root /var/www/projectLEMP;
    
         index index.html index.php;
    
         location / {
             try_files $uri $uri/ =404;
         }
    
         location ~ \.php$ {
             include snippets/fastcgi-php.conf;
             fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
         }
    
         location ~ /\.ht {
             deny all;
         }
     }
    
  3. Enable the configuration:

     sudo ln -s /etc/nginx/sites-available/projectLEMP /etc/nginx/sites-enabled/
     sudo nginx -t  # Test the configuration
    
  4. Disable the default configuration:

     sudo unlink /etc/nginx/sites-enabled/default
    
  5. Restart Nginx:

     sudo systemctl restart nginx
    

At this point, Nginx is ready to process PHP files.

Step 6: Setting Up the Database

We need to create a MySQL database and table to store tasks for a simple PHP todo list app.

Log in to the MySQL shell:

sudo mysql -p

Create a new database, user, and table:

CREATE DATABASE test_db;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'Password.1';
GRANT ALL PRIVILEGES ON test_db.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

USE test_db;
CREATE TABLE todo_list (
    item_id INT AUTO_INCREMENT,
    content VARCHAR(255),
    PRIMARY KEY(item_id)
);

Next, insert some data into the todo_list table:

INSERT INTO todo_list (content) VALUES ('My first important item');
INSERT INTO todo_list (content) VALUES ('My second important item');
INSERT INTO todo_list (content) VALUES ('My third important item');

Step 7: Creating a Simple PHP Application

Let’s now create a basic PHP file to display the tasks in our todo_list database.

Create the PHP File:

sudo nano /var/www/projectLEMP/todo_list.php

Add the Following PHP Code:

<?php
$user = 'testuser';
$password = 'Password.1';
$database = 'test_db';
$table = 'todo_list';

try {
    $db = new PDO('mysql:host=localhost;dbname=' . $database, $user, $password);
    echo '<h2>Todo List</h2><ol>';
    $todo_list = $db->query("SELECT content FROM $table");

    foreach($todo_list as $row) {
        echo '<li>' . $row['content'] . '</li>';
    }

    echo '</ol>';
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage() . '<br/>';
    die();
}
?>

Step 8: Testing the Application

Navigate to your EC2 instance’s public IP in a browser to test your PHP app:

http://<ec2-instance-public-ip>/todo_list.php

You should see the list of tasks from your MySQL database displayed in your browser.

Conclusion

Congratulations! You’ve successfully set up a LEMP stack on an AWS EC2 instance. This stack is a powerful combination that can handle a wide variety of web applications, from simple blogs to complex dynamic websites.

Recap of What We Did:

  1. Launched an EC2 instance running Ubuntu.

  2. Installed and configured Nginx as the web server.

  3. Installed MySQL and set up a database.

  4. Installed PHP and configured Nginx to process PHP files.

  5. Created a simple PHP application to interact with the MySQL database.

If you’re interested in further development, consider adding a domain name, configuring SSL certificates, or scaling your application using AWS services like Elastic Load Balancing and Auto Scaling.

References

0
Subscribe to my newsletter

Read articles from Engr. Animashaun Fisayo Michael directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Engr. Animashaun Fisayo Michael
Engr. Animashaun Fisayo Michael

Frontend Developer | Javascript programmer | Registered Mechanical Engineer (MNSE, COREN) | Facilities Management Technologies Developer