0% found this document useful (0 votes)
291 views

Create A Web Server and An Amazon RDS Database

This tutorial helps you create an Apache web server with PHP that connects to a MySQL database hosted on an Amazon RDS instance. You launch an EC2 instance in a VPC to host the web server and create an RDS DB instance in private subnets of the same VPC. You install Apache and PHP on the EC2 instance and connect the web server to the RDS database using the database endpoint.

Uploaded by

Anshul Kathet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
291 views

Create A Web Server and An Amazon RDS Database

This tutorial helps you create an Apache web server with PHP that connects to a MySQL database hosted on an Amazon RDS instance. You launch an EC2 instance in a VPC to host the web server and create an RDS DB instance in private subnets of the same VPC. You install Apache and PHP on the EC2 instance and connect the web server to the RDS database using the database endpoint.

Uploaded by

Anshul Kathet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Create a Web Server and an Amazon RDS Database

This tutorial helps you install an Apache web server with PHP, and create a MySQL database. The
web server runs on an Amazon EC2 instance using Amazon Linux, and the MySQL database is an
Amazon RDS MySQL DB instance. Both the Amazon EC2 instance and the Amazon RDS DB instance
run in a virtual private cloud (VPC) based on the Amazon VPC service.

Note

This tutorial works with Amazon Linux and might not work for other versions of Linux such as
Ubuntu.

Before you begin this tutorial, you must have a VPC with both public and private subnets, and
corresponding security groups. If you don't have these, complete the following tasks in Tutorial:
Create an Amazon VPC for Use with a DB Instance:

 Create a VPC with Private and Public Subnets

 Create Additional Subnets

 Create a VPC Security Group for a Public Web Server

 Create a VPC Security Group for a Private DB Instance

 Create a DB Subnet Group

In the tutorial that follows, you specify the VPC, subnets, and security groups when you create the
DB instance. You also specify them when you create the EC2 instance that will host your web server.
The VPC, subnets, and security groups are required for the DB instance and the web server to
communicate. After the VPC is set up, this tutorial shows you how to you create the DB instance and
install the web server. You connect your web server to your RDS DB instance in the VPC using the DB
instance endpoint.

In this tutorial, you perform the following procedures:


Step 1: Create an RDS DB Instance

Step 2: Create an EC2 Instance and Install a Web Server

The following diagram shows the configuration when the tutorial is complete.

VPC and EC2 security group Scenario

Step 1: Create an RDS DB Instance

In this step, you create an Amazon RDS MySQL DB instance that maintains the data used by a web
application.

Important

Before you begin this step, you must have a VPC with both public and private subnets, and
corresponding security groups. If you don't have these, see Tutorial: Create an Amazon VPC for Use
with a DB Instance. Complete the steps in Create a VPC with Private and Public Subnets, Create
Additional Subnets, Create a VPC Security Group for a Public Web Server, and Create a VPC Security
Group for a Private DB Instance.

Note
A new console interface is available for database creation. Choose either the New Console or
the Original Console instructions based on the console that you are using. The New
Console instructions are open by default.

New Console

To launch a MySQL DB instance

Sign in to the AWS Management Console and open the Amazon RDS console
at https://console.aws.amazon.com/rds/.

In the upper-right corner of the AWS Management Console, choose the AWS Region in which you
want to create the DB instance. This example uses the US West (Oregon) Region.

In the navigation pane, choose Databases.

Choose Create database.

On the Create database page, shown following, make sure that the Standard Create option is


chosen, and then choose MySQL.
In the Templates section, choose Dev/Test.

In the Settings section, set these values:

DB instance identifier – tutorial-db-instance

Master username – tutorial_user

Auto generate a password – Disable the option

Master password – Choose a password.

Confirm password – Retype the password.


In the DB instance size section, set these values:

DB instance performance type – Burstable

DB instance class – db.t2.small

In the Storage and Availability & durability sections, use the default values.

In the Connectivity section, open Additional connectivity configuration and set these values:


Virtual Private Cloud (VPC) – Choose an existing VPC with both public and private subnets, such as
the tutorial-vpc (vpc-identifier) created in Create a VPC with Private and Public Subnets

Note

The VPC must have subnets in different Availability Zones.

Subnet group – The DB subnet group for the VPC, such as the tutorial-db-subnet-group created
in Create a DB Subnet Group

Publicly accessible – No

VPC security groups – Choose an existing VPC security group that is configured for private access,
such as the tutorial-db-securitygroup created in Create a VPC Security Group for a Private DB
Instance.

Remove other security groups, such as the default security group, by choosing the X associated with
each.

Availability zone – No Preference

Database port – 3306
Open the Additional configuration section, and enter sample for Initial database name. Keep the
default settings for the other options.

To create your Amazon RDS MySQL DB instance, choose Create database.

Your new DB instance appears in the Databases list with the status Creating.

Wait for the Status of your new DB instance to show as Available. Then choose the DB instance
name to show its details.
In the Connectivity & security section, view the Endpoint and Port of the DB instance.

Note the endpoint and port for your DB instance. You use this information to connect your web
server to your RDS DB instance.

To make sure your RDS MySQL DB instance is as secure as possible, verify that sources outside of the
VPC can't connect to your RDS MySQL DB instance.

Step 2: Create an EC2 Instance and Install a Web Server

In this step you create a web server to connect to the Amazon RDS DB instance that you created
in Step 1: Create an RDS DB Instance.

Launch an EC2 Instance

First you create an Amazon EC2 instance in the public subnet of your VPC.
To launch an EC2 instance

Sign in to the AWS Management Console and open the Amazon EC2 console
at https://console.aws.amazon.com/ec2/.

Choose EC2 Dashboard, and then choose Launch Instance, as shown following.

Choose the Amazon Linux AMI, as shown following.


Important

Don't choose Amazon Linux 2 AMI because it doesn't have the software packages required for this
tutorial.

Choose the t2.small instance type, as shown following, and then choose Next: Configure Instance
Details.

On the Configure Instance Details page, shown following, set these values and leave the other values
as their defaults:

Network: Choose the VPC with both public and private subnets that you chose for the DB instance,
such as the tutorial-vpc (vpc-identifier) created in Create a VPC with Private and Public Subnets.

Subnet: Choose an existing public subnet, such as subnet-identifier | Tutorial public | us-west-


2a created in Create a VPC Security Group for a Public Web Server.

Auto-assign Public IP: Choose Enable.


Choose Next: Add Storage.

On the Add Storage page, keep the default values and choose Next: Add Tags.

On the Add Tags page, shown following, choose Add Tag, then enter Name for Key and


enter tutorial-web-server for Value.

Choose Next: Configure Security Group.

On the Configure Security Group page, shown following, choose Select an existing security group,


and then choose an existing security group, such as the tutorial-securitygroup created in Create a
VPC Security Group for a Public Web Server. The security group must include inbound rules for SSH
and HTTP access.
Choose Review and Launch.

On the Review Instance Launch page, shown following, verify your settings and then choose Launch.

On the Select an existing key pair or create a new key pair page, shown following, choose Create a
new key pair and set Key pair name to tutorial-key-pair. Choose Download Key Pair, and then save
the key pair file on your local machine. You use this key pair file to connect to your EC2 instance.
To launch your EC2 instance, choose Launch Instances. On the Launch Status page, shown following,
note the identifier for your new EC2 instance, for example: i-0288d65fd4470b6a9.
To find your instance, choose View Instances.

Wait until Instance Status for your instance reads as running before continuing.

Install an Apache Web Server with PHP

Next you connect to your EC2 instance and install the web server.

To connect to your EC2 instance and install the Apache web server with PHP

To connect to the EC2 instance that you created earlier, follow the steps in Connect to Your Linux
Instance.

To get the latest bug fixes and security updates, update the software on your EC2 instance by using
the following command:

Note

The -y option installs the updates without asking for confirmation. To examine updates before
installing, omit this option.

[ec2-user ~]$ sudo yum update -y

After the updates complete, install the Apache web server with the PHP software package using
the yum install command, which installs multiple software packages and related dependencies at the
same time.
[ec2-user ~]$ sudo yum install -y httpd24 php56 php56-mysqlnd

Note

If you receive the error No package package-name available, then your instance was not launched
with the Amazon Linux AMI (perhaps you are using the Amazon Linux 2 AMI instead). You can view
your version of Amazon Linux with the following command.

cat /etc/system-release

For more information, see Updating Instance Software.

Start the web server with the command shown following.

[ec2-user ~]$ sudo service httpd start

You can test that your web server is properly installed and started by entering the public DNS name
of your EC2 instance in the address bar of a web browser, for example: http://ec2-42-8-168-21.us-
west-1.compute.amazonaws.com. If your web server is running, then you see the Apache test page.
If you don't see the Apache test page, then verify that your inbound rules for the VPC security group
that you created in Tutorial: Create an Amazon VPC for Use with a DB Instance include a rule
allowing HTTP (port 80) access for the IP address you use to connect to the web server.

Note

The Apache test page appears only when there is no content in the document root
directory, /var/www/html. After you add content to the document root directory, your content
appears at the public DNS address of your EC2 instance instead of the Apache test page.

Configure the web server to start with each system boot using the chkconfig command.

[ec2-user ~]$ sudo chkconfig httpd on

To allow ec2-user to manage files in the default root directory for your Apache web server, you need
to modify the ownership and permissions of the /var/www directory. In this tutorial, you add a
group named www to your EC2 instance, and then you give that group ownership of
the /var/www directory and add write permissions for the group. Any members of that group can
then add, delete, and modify files for the web server.

To set file permissions for the Apache web server

Add the www group to your EC2 instance with the following command.

[ec2-user ~]$ sudo groupadd www

Add the ec2-user user to the www group.


[ec2-user ~]$ sudo usermod -a -G www ec2-user

To refresh your permissions and include the new www group, log out.

[ec2-user ~]$ exit

Log back in again and verify that the www group exists with the groups command.

[ec2-user ~]$ groups

ec2-user wheel www

Change the group ownership of the /var/www directory and its contents to the www group.

[ec2-user ~]$ sudo chgrp -R www /var/www

Change the directory permissions of /var/www and its subdirectories to add group write permissions
and set the group ID on subdirectories created in the future.

[ec2-user ~]$ sudo chmod 2775 /var/www

[ec2-user ~]$ find /var/www -type d -exec sudo chmod 2775 {} +

Recursively change the permissions for files in the /var/www directory and its subdirectories to add
group write permissions.

[ec2-user ~]$ find /var/www -type f -exec sudo chmod 0664 {} +

Connect your Apache web server to your RDS DB instance

Next, you add content to your Apache web server that connects to your Amazon RDS DB instance.

To add content to the Apache web server that connects to your RDS DB instance

While still connected to your EC2 instance, change the directory to /var/www and create a new
subdirectory named inc.

[ec2-user ~]$ cd /var/www

[ec2-user ~]$ mkdir inc

[ec2-user ~]$ cd inc

Create a new file in the inc directory named dbinfo.inc, and then edit the file by calling nano (or the
editor of your choice).
[ec2-user ~]$ >dbinfo.inc

[ec2-user ~]$ nano dbinfo.inc

Add the following contents to the dbinfo.inc file, where db_instance_endpoint is the endpoint of


your RDS MySQL DB instance, without the port, and master password is the master password for
your RDS MySQL DB instance.

Note

Placing the user name and password information in a folder that is not part of the document root for
your web server reduces the possibility of your security information being exposed.

<?php

define('DB_SERVER', 'db_instance_endpoint');

define('DB_USERNAME', 'tutorial_user');

define('DB_PASSWORD', 'master password');

define('DB_DATABASE', 'sample');

?>

Save and close the dbinfo.inc file.

Change the directory to /var/www/html.

[ec2-user ~]$ cd /var/www/html

Create a new file in the html directory named SamplePage.php, and then edit the file by calling nano
(or the editor of your choice).

[ec2-user ~]$ >SamplePage.php

[ec2-user ~]$ nano SamplePage.php

Add the following contents to the SamplePage.php file:

Note

Placing the user name and password information in a folder that is not part of the document root for
your web server reduces the possibility of your security information being exposed.

<?php include "../inc/dbinfo.inc"; ?>


<html>

<body>

<h1>Sample page</h1>

<?php

/* Connect to MySQL and select the database. */

$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);

if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

$database = mysqli_select_db($connection, DB_DATABASE);

/* Ensure that the EMPLOYEES table exists. */

VerifyEmployeesTable($connection, DB_DATABASE);

/* If input fields are populated, add a row to the EMPLOYEES table. */

$employee_name = htmlentities($_POST['NAME']);

$employee_address = htmlentities($_POST['ADDRESS']);

if (strlen($employee_name) || strlen($employee_address)) {

AddEmployee($connection, $employee_name, $employee_address);

?>

<!-- Input form -->

<form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">

<table border="0">

<tr>

<td>NAME</td>

<td>ADDRESS</td>

</tr>
<tr>

<td>

<input type="text" name="NAME" maxlength="45" size="30" />

</td>

<td>

<input type="text" name="ADDRESS" maxlength="90" size="60" />

</td>

<td>

<input type="submit" value="Add Data" />

</td>

</tr>

</table>

</form>

<!-- Display table data. -->

<table border="1" cellpadding="2" cellspacing="2">

<tr>

<td>ID</td>

<td>NAME</td>

<td>ADDRESS</td>

</tr>

<?php

$result = mysqli_query($connection, "SELECT * FROM EMPLOYEES");

while($query_data = mysqli_fetch_row($result)) {

echo "<tr>";

echo "<td>",$query_data[0], "</td>",

"<td>",$query_data[1], "</td>",

"<td>",$query_data[2], "</td>";
echo "</tr>";

?>

</table>

<!-- Clean up. -->

<?php

mysqli_free_result($result);

mysqli_close($connection);

?>

</body>

</html>

<?php

/* Add an employee to the table. */

function AddEmployee($connection, $name, $address) {

$n = mysqli_real_escape_string($connection, $name);

$a = mysqli_real_escape_string($connection, $address);

$query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";

if(!mysqli_query($connection, $query)) echo("<p>Error adding employee data.</p>");

/* Check whether the table exists and, if not, create it. */


function VerifyEmployeesTable($connection, $dbName) {

if(!TableExists("EMPLOYEES", $connection, $dbName))

$query = "CREATE TABLE EMPLOYEES (

ID int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

NAME VARCHAR(45),

ADDRESS VARCHAR(90)

)";

if(!mysqli_query($connection, $query)) echo("<p>Error creating table.</p>");

/* Check for the existence of a table. */

function TableExists($tableName, $connection, $dbName) {

$t = mysqli_real_escape_string($connection, $tableName);

$d = mysqli_real_escape_string($connection, $dbName);

$checktable = mysqli_query($connection,

"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t' AND


TABLE_SCHEMA = '$d'");

if(mysqli_num_rows($checktable) > 0) return true;

return false;

?>

Save and close the SamplePage.php file.

Verify that your web server successfully connects to your RDS MySQL DB instance by opening a web
browser and browsing to http://EC2 instance endpoint/SamplePage.php, for example: http://ec2-55-
122-41-31.us-west-2.compute.amazonaws.com/SamplePage.php.
You can use SamplePage.php to add data to your RDS MySQL DB instance. The data that you add is
then displayed on the page.

To make sure your RDS MySQL DB instance is as secure as possible, verify that sources outside of the
VPC cannot connect to your RDS MySQL DB instance.

You might also like