YouTube video demonstration of how to set up an EC2 instance and install LAMP stack on Amazon Linux 2023

Introduction

A “LAMP” stack is a group of open source software that is typically installed together in order to enable a server to host dynamic websites and web applications written in PHP. The term is an acronym which represents the Linux operating system, Apache web server, MySQL database and PHP.

This guide will show you how to set up an Amazon Elastic Compute Cloud (EC2) instance and install LAMP stack on an Amazon Linux 2023 server. It will also show you how to store data in a MariaDB relational database, retrieve the data and serve it on a web page.

Prerequisites

In order to complete this tutorial, you will need to have an Amazon Web Services (AWS) account.

Step 1 – Set up: Create a key pair

  1. Open the Amazon EC2 console 
  2. In the navigation pane, choose Key Pairs.
  3. Choose Create key pair.
  4. For Name, enter a descriptive name for the key pair. Eg tutorial-ec2-key-pair
  5. For Key pair type, choose RSA.
  6. For Private key file format, choose the format in which to save the private key. E.g. choose .pem, a format that can be used with OpenSSH.
  7. Choose Create key pair.
  8. The private key file is automatically downloaded by your browser. Save the private key file in a safe place. (This is the only chance for you to save the private key file.)
  9. If you plan to use an SSH client on a macOS or Linux computer to connect to your Linux instance, use the following command to set the permissions of your private key file so that only you can read it.
chmod 400 key-pair-name.pem

If you do not set these permissions, then you cannot connect to your instance using this key pair.

Step 2 – Create a security group

Security groups act as a firewall for associated instances, controlling both inbound and outbound traffic at the instance level. You must add rules to a security group that enable you to connect to your instance from your IP address using SSH. You can also add rules that allow inbound and outbound HTTP and HTTPS access from anywhere.

To create a security group with least privilege

i) Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/

ii) From the top navigation bar, select an AWS Region for the security group. Security groups are specific to a Region, so you should select the same Region in which you created your key pair. 

iii) In the left navigation pane, choose Security Groups.

iv) Choose Create security group.

v) For Basic details, do the following:

  1. Enter a name for the new security group and a description. Use a name that is easy for you to remember, such as your user name, followed by _SG_, plus the Region name. For example, tutorial-ec2-access_SG_stockholm.
  2. In the VPC list, select your default VPC for the Region.

vi) For Inbound rules, create rules that allow specific traffic to reach your instance. For example, use the following rules for a web server that accepts HTTP and HTTPS traffic. 

  1. Choose Add rule. For Type, choose HTTP. For Source, choose Anywhere.
  2. Choose Add rule. For Type, choose HTTPS. For Source, choose Anywhere.
  3. Choose Add rule. For Type, choose SSH. For Source, choose Anywhere. (For security reasons this is not recommended for production environment).
  4. Click Create security group.

vii) For Outbound rules, keep the default rule, which allows all outbound traffic.

Step 3 – Launch an EC2 instance

To launch an instance

  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
  1. From the EC2 console dashboard, in the Launch instance box, choose Launch instance, and then choose Launch instance from the options that appear.
  2. Under Name and tags, for Name, enter a descriptive name for your instance. E.g. lamp-tutorial-web-server
  3. Under Application and OS Images (Amazon Machine Image), do the following:
    1. Choose Quick Start, and then choose Amazon Linux. This is the operating system (OS) for your instance.
    2. From Amazon Machine Image (AMI), select an HVM version of Amazon Linux 2. Notice that these AMIs are marked Free tier eligible. An Amazon Machine Image (AMI) is a basic configuration that serves as a template for your instance.
  4. Under Instance type, from the Instance type list, you can select the hardware configuration for your instance. Choose the t2.micro instance type, which is selected by default. The t2.micro instance type is eligible for the free tier. In Regions where t2.micro is unavailable, you can use a t3.micro instance under the free tier. 
  5. Under Key pair (login), for Key pair name, choose the key pair that you created when getting set up. (e.g tutorial-ec2-key-pair)

Warning

Do not choose Proceed without a key pair (Not recommended). If you launch your instance without a key pair, then you can’t connect to it.

  1. Next to Network settings, choose Edit. For Security group name, you’ll see that the wizard created and selected a security group for you. You can use this security group, or alternatively you can select the security group that you created when getting set up using the following steps:
    1. Choose Select existing security group.
    2. From Common security groups, choose your security group from the list of existing security groups. (e.g. tutorial-ec2-access_SG_stockholm)
  1. Keep the default selections for the other configuration settings for your instance.
  2. Review a summary of your instance configuration in the Summary panel, and when you’re ready, choose Launch instance.
  3. A confirmation page lets you know that your instance is launching. Choose View all instances to close the confirmation page and return to the console.
  4. On the Instances screen, you can view the status of the launch. It takes a short time for an instance to launch. When you launch an instance, its initial state is pending. After the instance starts, its state changes to running and it receives a public DNS name. If the Public IPv4 DNS column is hidden, choose the settings icon ( Settings icon. ) in the top-right corner, toggle on Public IPv4 DNS, and choose Confirm.
  5. It can take a few minutes for the instance to be ready for you to connect to it. Check that your instance has passed its status checks; you can view this information in the Status check column.

Step 4 – Install LAMP on Amazon Linux 2023 instance

  1. Connect to your instance. There are several ways to connect to your instance. I will connect from my computer using SSH
    1. From the instances page, click the Instance ID of your instance (lamp-tutorial-web-server).
    2. Click Connect button.
    3. Click SSH client tab.
    4. Open an SSH client on your computer
    5. Run the following command: chmod 400 your-key-pair-name (tutorial-ec2-key-pair.pem)
    6. Connect to your instance using its Public DNS: Eg. ssh -i “your-key-pair-name.pem” ec2-user@ec2-ip-address-region.compute.amazonaws.com
    7. Enter yes if asked: Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
  1. Perform a quick software update on your instance: 
sudo dnf update -y
  1. Install the latest versions of Apache web server and PHP packages for Amazon Linux 2023:  
sudo dnf install -y httpd wget php-fpm php-mysqli php-json php php-devel

4. Install the MariaDB software packages. Use the dnf install command to install multiple software packages and all related dependencies at the same time: 

sudo dnf install mariadb105-server 
  1. Type y when prompted to install the MariaDB server

You can view the current versions of these packages using the following command: sudo dnf info package_name

  1. Start the Apache web server: 
sudo systemctl start httpd
  1. Use the systemctl command to configure the Apache web server to start at each system boot: 
sudo systemctl enable httpd

You can verify that httpd is on by running the following command:

sudo systemctl is-enabled httpd

NOTE: There should be a security rule to allow inbound HTTP (port 80) connections as part of set up steps. Verify.

  1. Test your web server. In a web browser, type the public DNS address (or the public IP address) of your instance. If there is no content in /var/www/html, you should see the Apache test page, which will display the message “It works!”.

To allow the ec2-user account to manipulate files in the Apache document root directory (/var/www/html), you must modify the ownership and permissions of the directory. In this tutorial, I will add ec2-user to the apache group to give the apache group ownership of the /var/www directory and assign write permissions to the group.

To set file permissions

  1. Add your user (in this case, ec2-user) to the apache group: 
sudo usermod -a -G apache ec2-user
  1. Log out and then log back in again to pick up the new group, and then verify your membership.
    1. Log out (use the exit command or close the terminal window): exit
    2. To verify your membership in the apache group, reconnect to your instance, and then run the following command: 
groups

Output: ec2-user adm wheel apache systemd-journal

  1. Change the group ownership of /var/www and its contents to the apache group: 
sudo chown -R ec2-user:apache /var/www
  1. To add group write permissions and to set the group ID on future subdirectories, change the directory permissions of /var/www and its subdirectories: 
sudo chmod 2775 /var/www && find /var/www -type d -exec sudo chmod 2775 {} \;
  1. To add group write permissions, recursively change the file permissions of /var/www and its subdirectories: 
find /var/www -type f -exec sudo chmod 0664 {} \;

Now, ec2-user (and any future members of the apache group) can add, delete, and edit files in the Apache document root, enabling you to add content, such as a static website or a PHP application.

Step 5: Test LAMP server

  1. Create a PHP file in the Apache document root:
echo “<?php phpinfo(); ?>” > /var/www/html/phpinfo.php

NOTE: If you get a “Permission denied” error when trying to run this command, try logging out and logging back in again to pick up the proper group permissions that you configured in To set file permissions.

  1. In a web browser, type the URL of the file that you just created. This URL is the public DNS address of your instance followed by a forward slash and the file name. For example: http://my.public.dns.amazonaws.com/phpinfo.php

You should see the PHP information page:

  1. Delete the phpinfo.php file. Although this can be useful information, it should not be broadcast to the internet for security reasons.
rm /var/www/html/phpinfo.php

You should now have a fully functional LAMP web server. If you add content to the Apache document root at /var/www/html, you should be able to view that content at the public DNS address for your instance.

Step 6: Secure the database server

The default installation of the MariaDB server has several features that are great for testing and development, but they should be disabled or removed for production servers. The mysql_secure_installation command walks you through the process of setting a root password and removing the insecure features from your installation. 

To secure the MariaDB server

  1. Start the MariaDB server:
sudo systemctl start mariadb
  1. Run mysql_secure_installation.
sudo mysql_secure_installation

i) When prompted to type the current root password: By default, the root account does not have a password set. Press Enter.

ii) Type Y when prompted Switch to unix_socket authentication [Y/n]

iii) Type Y when prompted Change the root password? to set a password, and type a secure password twice. Make sure to store this password in a safe place.

Setting a root password for MariaDB is only the most basic measure for securing your database. When you build or install a database-driven application, you typically create a database service user for that application and avoid using the root account for anything but database administration.

iii) Type Y to remove the anonymous user accounts.

iv) Type Y to disable the remote root login.

v) Type Y to remove the test database.

vi) Type Y to reload the privilege tables and save your changes.

(Optional) To get the MariaDB server to start at every boot, type the following command:

sudo systemctl enable mariadb

Step 7 – Testing Database Connection from PHP

i) Login to MariDB server and enter password when prompted.

sudo mysql -u root -p

ii) Create a database named sample_database.

CREATE DATABASE sample_database;

iii) Create a user in the database.

CREATE USER 'sample_user'@'%' IDENTIFIED BY 'User@789dynamic!';

iv) Grant permissions on sample_database to sample_user.

GRANT ALL ON sample_database.* TO 'sample_user'@'%';

v) Create a todo_list table.

CREATE TABLE sample_database.todo_list ( item_id INT AUTO_INCREMENT, content VARCHAR(255), PRIMARY KEY(item_id));

vi) Insert data into todo_list

INSERT INTO sample_database.todo_list (content) VALUES ("My first important item");
INSERT INTO sample_database.todo_list (content) VALUES ("My second important item");
INSERT INTO sample_database.todo_list (content) VALUES ("My third important item");

vii) Let’s query the database.

select * from sample_database.todo_list;

viii) Exit MariaDB.

exit;

viii) Change to the web server document root directory:

cd /var/www/html

Enter the following command to create my-sample-data.php script: 

sudo nano my-sample-data.php

Copy and paste the following in the my-sample-data.php page

<?php
$user = "sample_user";
$password = "User@789dynamic!";
$database = "sample_database";
$table = "todo_list";
try {
  $db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);

  echo "<h2>TODO</h2><ol>";
  foreach($db->query("SELECT content FROM $table") as $row) {
    echo "<li>" . $row['content'] . "</li>";
  }
  echo "</ol>";
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

Save the changes.

View the page over the internet using your browser: E.g go to ip.address/my-sample-data.php

Conclusion

In this tutorial you learned:

i) How to set up an Amazon EC2 instance on AWS;

ii) How to install LAMP stack on an EC2 instance;

iii) How to populate a MariaDB database with data and write a web page script to retrieve the data and display it on a web page;

iv) How to test that the dynamic web page worked using a web browser.

References

  1. Set up to use Amazon EC2.
  2. Tutorial: Get Started with Amazon EC2 Linux Instances
  3. Install LAMP on Amazon Linux 2023
  4. How to sign up for your own AWS account.
  5. Caseray Cloud
  6. My (Ugochukwu Ukwuegbu’s) YouTube channel.

3 replies on “How to setup an Amazon Elastic Compute Cloud instance and install Linux, Apache, MariaDB and PHP (LAMP Stack) on Amazon Linux 2023”

Comments are closed.