Install PHP & MySQL on Amazon Linux EC2

This guide walks you through setting up a LAMP stack (Linux, Apache, PHP, MySQL) on an Amazon Linux 2023 EC2 instance. By the end, you'll have a working web server with PHP and a MySQL database.

1. Prerequisites

Connect to your instance:

ssh -i "your-key.pem" ec2-user@your-public-ip

2. Update the System

Always update packages before installing new software:

sudo dnf update -y
Note: Amazon Linux 2023 uses dnf. For Amazon Linux 2, use yum.

3. Install Apache (httpd)

sudo dnf install -y httpd sudo systemctl start httpd sudo systemctl enable httpd

Verify Apache is running:

sudo systemctl status httpd

You should now see the Apache test page at http://your-public-ip.

4. Install PHP

Install PHP and common extensions:

sudo dnf install -y php php-cli php-fpm php-mysqlnd php-xml php-mbstring php-curl php-zip php-json

Verify the PHP version:

php -v

Restart Apache to load PHP:

sudo systemctl restart httpd

5. Install MySQL

Install the MySQL community server:

sudo dnf install -y mysql-community-server

Start and enable MySQL:

sudo systemctl start mysqld sudo systemctl enable mysqld

Find the temporary root password generated on first start:

sudo grep 'temporary password' /var/log/mysqld.log

6. Secure MySQL

Run the built-in security script to set a root password and remove insecure defaults:

sudo mysql_secure_installation

Follow the prompts to:

Log in to MySQL to verify:

mysql -u root -p

7. Test PHP

Create a PHP info file to confirm PHP is working with Apache:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

Visit http://your-public-ip/info.php in a browser. You should see the PHP information page.

Security tip: Delete this file after testing — it exposes server details. sudo rm /var/www/html/info.php

8. Verify Installation

Run a quick check on all services:

sudo systemctl status httpd sudo systemctl status mysqld php -v mysql --version

Your LAMP stack is now ready. You can deploy PHP applications, WordPress, or Laravel on this EC2 instance.

Related: Back to AWS EC2 Tutorial