LAMP (Linux, Apache, MySQL, PHP) web server on an Amazon EC2 Linux instance
This medium post will guide you through the creation of an AWS EC2 Linux instance, the installation and configuration of a LAMP web server within that instance and the creation of php twitter like application called Parrot. This guide assumes the developer already has an active AWS account.
Launching your AWS Instance
To start with you need to create an EC2 Linux instance via Amazon Web Services. Log in to your AWS account and from the web console chose EC2 under the Compute heading.
From within the EC2 dashboard, you need to select Launch Instance.
A set up wizard should begin in which the user selects an Amazon Machine Image or AMI and then configures it. First, Step 1 allows the user to select the image. Choose the option titled Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type — ami-6b8cef13. It should be covered under the free tier choices.
Next, Step 2 prompts the user to choose an Instance Type. Choose the version titled “t2.micro” under “Type” column. It should have the subtext stating it is “Free tier eligible”. It may be selected by default. Once the Instance Type is selected, click “Next: Configure Instance Details” down in the bottom right of the wizard.
Skip Step 4 and Step 5 by clicking the Next button down at the bottom right of the page, until you arrive at Step 6. Configure Security Group. From here we need to open some ports for our LAMP web server. The SSH rule should be added by default, if not, select SSH from the drop-down menu under Type, then under the source column, choose “Anywhere”. Next, choose add rule, then select HTTP from the Type drop-down menu and again “Anywhere” under the source column. After that, select Add Rule again, and this time chose HTTPS from the Type drop-down menu and again choose “Anywhere” as the Source. Finally, add the last rule by choosing MYSQL/AURORA from the Type drop-down menu and “Anywhere” under source. Check that your security group configuration looks similar to the screenshot below before choosing “Review and Launch”.
On the next screen review your security group one last time and ensure it matches the settings outlined above. Once everything looks fine choose Launch.
Once “Launch” is selected, the user is prompted to create a new Key Pair group. To to this choose “Create a new key pair”. Under “Key Pair Name” type in a name of your choosing, then click the “Download Key Pair” button. You will be then prompted to save this key. Make sure to save this somewhere safe, but also somewhere you will remember. Amazon does not allow users to log into machines via a username and passwords, instead you will use keys. So its important not to to misplace or lose the key. Once that is completed and your key is saved, select launch instance.
The instance can take a while to configure, but once its finished select View Instances from the bottom right to view your own instances and some of their configurations. At the moment their should only be one instance present. It make take a few minutes for your machine to instantiate, when its ready to go, it will display a green dot beside the word running under the “Instance State” column.
Connect To Your Instance
This guide will cover connecting to your AWS instance on a windows machine via Putty. If you are using a Unix based operating system, such as Linux or Mac OS X there a plenty of guides online, including Amazons own set of instructions, available by navigating to step 2 in the guide below.
Step 1 — Download and Install PuTTY
Download the latest PuTTY release from the link below and download the installer, either 32-bit or 64-bit depending on your operating system, and install it to your machine
If PuTTY is installed correctly, the user should have the option of opening PuTTY or PuTTYgen.
Step 2 — Generating a Private Key File
First to begin generating a Private Key File open PuTTYgen. Once open, ensure the RSA radio button is selected under Parameters.
Next select the Load option Load. You will be then prompted to choose the .pem key pair your generated earlier. Navigate to where you saved the Key Pair created in the earlier section. If it does not appear in the location it was saved, choose All Files (*.*) from the drop-down menu at the bottom right. It should be of the file type .pem. Once the key pair is loaded and your back at the PuTTY Key Generator, select “Save Private Key”, choose Yes when prompted and save the file in the same location as the Key Pair used earlier. Ensure it has the extension .ppk when saving it. Once saved, close PuTTYgen.
Step 3 — Connecting to your AWS Instance with PuTTY
The next step involves using the newly generated ppk from the previous step and connecting to the command-line interface (CLI) of your AWS Instance. First, open PuTTY (not PuTTYgen from the last step). PuTTY asks to user for the Host Name (or IP address) of the AWS instance they would like to connect to. To find this Host Name navigate back to your AWS EC2 Management Console. From here find your Public DNS (IPv4) in the bottom panel, as shown below in the part highlighted in yellow. Copy this address.
Return to PuTTY and add the prefix ec2-user@ to the field where it requests your Host Name, followed by the Public DNS your just copied from the EC2 Management Console. It should look something like this but with your own details:
ec2-user@ ec2–00–000–00–00.us-west-2.compute.amazonaws.com
And should look like this in PuTTY:
Don’t press Open just yet, next we need to add our pkk key. Without changing anything from the previous section, navigate to Connection — SSH — Auth via the PuTTY side menu.
Next select browse and navigate to where you saved your .ppk and double click it . Do not select Open yet but navigate back to “Session” via the PuTTY side menu. From here, in the field with the title “Saved Sessions” enter a title you would like this instance to be named going forward and then select Save. For any future sessions, a double click of this name will open and authenticate your AWS Instance.
You can now select Open and connect to your AWS instance.
Install and start the LAMP web server
If you not already, connect to your instance like we did in the previous step.
To ensure that all of your software packages are up to date, perform a quick software update on your instance. This process may take a few minutes, but it is important to make sure that you have the latest security updates and bug fixes. The -y
option installs the updates without asking for confirmation. If you would like to examine the updates before installing, you can omit this option.
sudo yum update -y
Now that your instance is current, you can install the Apache web server, MySQL, and PHP software packages.
sudo yum install -y httpd24 php70 mysql56-server php70-mysqlnd
Start the Apache web server.
sudo service httpd start
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. You can get the public DNS for your instance using the Amazon EC2 console (check the Public DNS column; if this column is hidden, choose Show/Hide Columns (the gear-shaped icon) and choose Public DNS).
Apache httpd serves files that are kept in a directory called the Apache document root. The Amazon Linux Apache document root is /var/www/html
, which by default is owned by root.
ls -l /var/www
To allow the ec2-user account to manipulate files in this directory, you must modify the ownership and permissions of the directory. There are many ways to accomplish this task. In this tutorial, you add the ec2-user user to the apache
group, to give the apache
group ownership of the /var/www
directory and assign write permissions to the group.
Setting file permissions
Add your user (in this case, ec2-user) to the apache
group.
sudo usermod -a -G apache ec2-user
Log out and then log back in again to pick up the new group, and then verify your membership.
Log out (use the exit command or close the terminal window):
exit
To verify your membership in the apache
group, reconnect to your instance, and then run the following command:
groups
Change the group ownership of /var/www
and its contents to the apache
group.
sudo chown -R ec2-user:apache /var/www
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
Then:
find /var/www -type d -exec sudo chmod 2775 {} \;
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, the ec2-user user (and any future members of the apache
group) can add, delete, and edit files in the Apache document root. Now you are ready to add content, such as a static website or a PHP application.
Test your LAMP server
Create a PHP file in the Apache document root.
echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
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 Set File Permissions.
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
Where my.public.dns.amazonaws.com
is your own public DNS.
You should see the PHP information page:
If you do not see this page, verify that the /var/www/html/phpinfo.php
file was created properly in the previous step. You can also verify that all of the required packages were installed with the following command. The package versions in the second column do not need to match this example output.
sudo yum list installed httpd24 php70 mysql56-server php70-mysqlnd
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
Secure the database server
Start the MySQL server.
sudo service mysqld start
Run mysql_secure_installation.
sudo mysql_secure_installation
When prompted, type a password for the root account. Type the current root password. By default, the root account does not have a password set. Press Enter. Type Y
to set a password, and type a secure password twice. Make sure the password chosen here will be one your remember, it will be used later to connect your LAMP application to the MySQL database.
- When prompted press y to remove anonymous user accounts.
- Type n to allow remote root login.
- Type
Y
to remove the test database. - Type
Y
to reload the privilege tables and save your changes.
Install phpMyAdmin
Important
It is not recommend to use phpMyAdmin to access a LAMP server unless you have enabled SSL/TLS in Apache; otherwise, your database administrator password and other data are transmitted insecurely across the internet. For security recommendations from the developers, see Securing your phpMyAdmin installation. For general information about securing a web server on an EC2 instance, see Tutorial: Configure Apache Web Server on Amazon Linux to use SSL/TLS.
To install phpMyAdmin, first install the required dependencies.
sudo yum install php70-mbstring.x86_64 php70-zip.x86_64 -y
Restart Apache.
sudo service httpd restart
Navigate to the Apache document root at /var/www/html
.
cd /var/www/html
Next we need to download the latest release of phpMyAdmin
wget https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.tar.gz
Extract the package.
tar -xvzf phpMyAdmin-latest-all-languages.tar.gz
Check the files in the current directory and note the name of the extracted phpMyAdmin version.
ls
Then change the name of the resulting directory to something more manageable. 4.7.5 below, will be changed the the version you noted in the last step.
mv phpMyAdmin-4.7.5-all-languages phpMyAdmin
If the MySQL server is not running, start it now.
sudo service mysqld start
In a web browser, type the URL of your phpMyAdmin installation. This URL is the public DNS address (or the public IP address) of your instance followed by a forward slash and the name of your installation directory. For example:
http://my.public.dns.amazonaws.com/phpMyAdmin
Where my.public.dns.amazonaws.com
is your own public DNS.
You should see the phpMyAdmin login page:
Log in to your phpMyAdmin installation with the root
user name and the MySQL root password you created earlier. We will come back to this in a moment.
Setting root permissions in phpMyAdmin
Before configuring the root permissions in phpMyAdmin, we first need to discover what the internal I.P. address of our EC2 instance is. To discover this type the following into your terminal:
ip a
This should return something similar to t he following.
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 12:31:41:02:58:47 brd ff:ff:ff:ff:ff:ff
inet **XX.XX.XX.XXX/23** brd YY.YYY.YY.YYY scope global eth0
inet6 fe80::1031:41ff:fe02:5847/64 scope link
valid_lft forever preferred_lft forever
The internal I.P. address of our EC2 instance is available at the third last line and in my case is XX.XX.XX.XXX/23
but will be different for everyone. Record this I.P. address as it will be needed to configure both phpMyAdmin root permissions as well as the host of our php application.
Once you have access to the internal I.P., log into phpMyAdmin and navigate to SQL via the top navigation bar.
Then enter the following SQL command. Where ‘XX.XX.XX.XXX/23
’ is your the internal I.P. address you just discovered and ‘password’ is the password you set configuring MySQL.
GRANT ALL PRIVILEGES ON *.* TO 'root'@'XX.XX.XX.XXX/23' IDENTIFIED BY 'password';
Creating the Database and Tables for the php Application
In phpMyAdmin, select new from the side menu to create a new database.
Name it ‘parrot’ (all lowercase and without the inverted commas), then select Create.
Select the newly created database from the side bar.
Then select SQL from the navigation bar.
Then copy and paste the following SQL commands into the text fields and press Go.
create Table members(
user VARCHAR(16),
pass VARCHAR(16),
INDEX(user(6)));
create Table messages (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
auth VARCHAR(16),
recip VARCHAR(16),
pm CHAR(1),
time INT UNSIGNED,
message VARCHAR(4096),
INDEX(auth(6)),
INDEX(recip(6)));
create Table friends(
user VARCHAR(16),
friend VARCHAR(16),
INDEX(user(6)),
INDEX(friend(6)));
create Table profiles(
user VARCHAR(16),
text VARCHAR(4096),
INDEX(user(6))
);
It should look like this within phpMyAdmin.
Cloning the php Application from GitHub
Now that the database is set up, and the tables are ready to be used, we need to create our php app.
Navigate back your terminal running on the AWS Instance. If your are not already in the Apache directory root, navigate their now.
cd /var/www/html
Now install git.
yum install git
Next clone the repository off the php application we are going to use too test our LAMP server.
git clone https://github.com/oreillyalan88/Parrot.git
Then move the newly cloned application from its cloned folder the html folder.
mv Parrot/* .
Then to remove the empty Parrot folder.
rm -r Parrot
Now we need to configure the php application so it uses our settings to talk to the MySQL database.
Configuring Robin
To enter our own details into the Robin configuration file, we need to use nano to edit the php files without terminal.
nano config.php
Once config.php is opened in the terminal it can be edited as if it was in a normal text editor. It should appear like so.
Navigate down to $dbhost and change it to the internal I.P. address of our EC2 instance that we made of note of earlier, minus the route. So instead of XX.XX.XX.XXX/23
it would be XX.XX.XX.XXX
. Next navigate down to $dbpass and change the ******** to the the password you configure for MySQL, in other word the password you used to log in in to phpMyAdmin. It should now look like similar to the screen grab below.
To save these changes press ctrl + x in nano, then press y when prompted, then finally press enter. The changes will be saved.
Restart both MySQL and httpd within the instance terminal.
sudo service mysqld restartsudo service httpd restart
Using The php Application Robin
Now that the databases are configured and the application is connected to the database and its tables, its time to use the application.
Navigate to your public DNS found in your EC2 Dashboard via the web browser. If all goes well and everything is properly configure you should be able to register and use the app. Congratulations, you have created your first LAMP web application using Amazon Web Services.