Connect a Web App with Aurora

Create a web app that runs on EC2 and connect it to Aurora DB.

Introduction

โšก๏ธ 30 second Summary

In this project, you'll be recreating one of THE most common use cases of cloud computing.

There are countless web apps on the Internet today, and engineers use databases all the time to store the web app's data e.g. login credentials, e-commerce product information, movie reviews... you name it!

Let's build a mini version of this pattern, by setting up a web app from scratch and connecting it with a relational database (Amazon Aurora) to store things that users input.

Get ready to:

  • ๐Ÿงฑ Create an Aurora MySQL Database.
  • ๐ŸŒ Build and connect a web app.
  • ๐Ÿ”— Connect your database to the web app!!
  • โœจ Make magic happen - enter data through your web app, and see the data get stored in your Aurora database.

Want a complete demo of how to do this project, from start to finish? Check out our ๐ŸŽฌ walkthrough with Maya ๐ŸŽฌ

If you're up for a bit of a challenge, quiz yourself on the key concepts up ahead in this project.

Before we start Step #1...

Before we get started, it's important that you know what we're trying to do today.

Login with your IAM user

For this project you'll need your IAM user, not your root user.

In this step, get ready to:

  • Create/log in as an IAM user

What is an IAM user? Why are we setting one up?

In AWS, a user is a person or a computer that can do things on the AWS cloud.

When you create an AWS account for the first time, the login you get is called the root user of the AWS account. AWS actually recommends to not use your root user for everyday tasks to protect it from security breaches.

You should create IAM users instead. If a root user is a master key to your AWS account, think of IAM users as key copies. IAM users have separate usernames and passwords to your root user, and you can set them to have limited access to your account's resources.

Do you have an IAM user?

Yes, and I have an IAM user

Awesome!

No, I need to create one

No worries - here are the steps to create one (this takes less than 10 mins).

  • Head to your AWS Account as the root user.
  • Open the AWS IAM console.
  • From the left hand navigation panel, choose Users.
  • Choose Create user.
  • For the User name, name it:
[[YOURNAME="enter your name"]]-IAM-Admin
  • Make sure to select the checkbox next to Provide user access to the AWS Management Console - optional.โ€

Note

This does not apply to all accounts, but if you're prompted with a pop up panel that says Are you providing access to a person?, choose I want to create an IAM user.โ€

  • For the console password, choose Custom password.
  • Type in a password that you will be able to remember/access in the future.

Top tip

You will use this password for all future projects, so make sure to choose a secure one!

  • Deselect the checkbox for Users must create a new password at next sign-in - Recommended.
  • Choose Next.
  • In the permissions set up page, choose Attach policies directly.
  • From the list of Permissions policies, select AdministratorAccess.
  • Choose Next.
  • Choose Create user.
  • Voilร  - you've just created your new user! Stay on this page.
  • Choose Download .csv file.
  • Copy the Console sign-in URL.
  • Now you're ready to start using your IAM user. ๐Ÿ
  • Log out of your root user's AWS Account.
  • Paste and go to your copied console sign-in URL.
  • Open your downloaded .csv file containing your user's access instructions.
  • Log in using your IAM user's username and password in the .csv file.

Note

PLEASE make sure you log in to your IAM Admin User instead of the root user - it's truly best practice for account security.

Launch an EC2 instance for your web app

In this step, we're going to create an Amazon EC2 instance using your account's default VPC and default subnets.

In this step, get ready to:

  • Create an EC2 instance to host your web app.

...and this is what it's going to look like:

  • Open a new tab in your web browser and go to your AWS console (this means we can keep our Aurora database set-up in progress!).
  • In the upper-right corner of the AWS Management Console, make sure you're picking the Region that's closest to you.
  • In the AWS console search bar, search for EC2.
  • Select Instances in the left hand menu and choose Launch instances.

Why do we need an EC2 instance to run a web app?

A web app needs to run on a computer. But are we going to go buy a physical computer to do this?

No! We're going to use a virtual computer that we rent through AWS. This is exactly what EC2 is here for. Think of an EC2 instance as a rented virtual computer that you use to run your web app. It's the place where all the processing, data handling, and user interactions happen.

  • Choose the following settings in the Launch an instance page.
    • Enter nextwork-ec2-instance-web-server for the instance's name.
    • Under Application and OS Images (Amazon Machine Image), choose Amazon Linux.
    • Choose the Amazon Linux 2023 AMI.
    • Keep the defaults for the other choices.
  • Under Instance type, choose t2.micro.
  • Under Key pair (login), choose a Create new key pair.

What is a key pair? Why are we creating one?

A key pair in EC2 is quite literally the keys to access our EC2 instance.

We need keys to our EC2 instance if we want to add, change, or update how our EC2 instance is running.

Since a EC2 instance is a virtual machine, a good way to think about key pairs is like the login credentials to your own computer...except it's all virtual!

  • For your Key pair name, enter NextWorkAuroraApp.
  • Leave your Key pair type as RSA.
  • Leave your Private key file format as .pem since we're using SSH later on to access our EC2 instance.
  • Select Create key pair.

A new file will automatically download to your computer - don't be alarmed!

This is your new key pair. We'll need it for later in the project to access our EC2 instance.

  • Back in our EC2 creation, under Network settings, set these values and keep the other values as their defaults:
    • For Allow SSH traffic from, choose your IP address if it's correct (you can check your IP by clicking here). Otherwise select Anywhere.
  • Check the boxes for Allow HTTP traffic from the internet.
  • Leave the default values for the remaining sections.
  • Review the Summary panel of your instance configuration

What does this Summary panel tell us?

๐Ÿ’ป Number of instances - the number of machines you're running.

๐ŸŽจ Software Image (AMI) - the operating system of your virtual machine.

โš™๏ธ Virtual server type - the CPU, memory, and network performance package you selected.

๐Ÿ‘ฎ Firewall - firewalls control the inbound and outbound traffic for your instances. In EC2, we use security groups for this.

๐Ÿชฃ Storage - the storage options for your instance.

  • When you're ready, choose Launch instance.
  • Navigate back to your list of EC2 instances, and then select the checkbox next to your new instance.
  • In the Details tab, note the following important details:
    • In Instance summary, note the Public IPv4 DNS:
    • YOUR_EC2_ADDRESS.
    • Note the value for Key pair assigned at launch.

What does the Public IPv4 DNS tell us?

Think about the Public IPv4 DNS as the location of a house, and then the Key pair assigned at launch like the keys that let you in. It's no good just having the location without any keys, and you can't have keys without knowing where to go! Both are critical for accessing our EC2 instance.

  • Wait until Instance state for your instance is Running before continuing.

Create an Aurora MySQL Database

Web server, tick! Now onto another key component - your database.

Let's set up an Aurora database in this step. After this, we can connect it to our web app and get cracking.

In this step, get ready to:

  • Create an Aurora relational database from scratch.

What IS a relational database? How is it different from a normal database?

A relational database is a type of database that organizes data into tables, which are collections of rows and columns. Kind of like a spreadsheet! We call it "relational" because the rows relate to the columns and vice-versa.

When a database is relational we can query it using a special language called SQL (Structured Query Language)

Strangely enough, there isn't really such a thing as a "normal" database. We have relational databases and non-relational databases (also known as NoSQL)... but that's for another project ๐Ÿค No spoilers!

  • Make sure you're in the same region as your web server EC2 instance.

Why does our Region matter?

We're working with a couple of different services today so we need to make sure we create them all in the same Region. Otherwise things are going to get very complicated on the networking side!

Let's create your Aurora database

  • Head to RDS console - search for rds in search bar at the top of the screen.
  • Notice that even if you search for Aurora, the same result shows up!
  • In the left navigation bar, select Databases.
  • In the Database section, select Create Database.
  • On the Create database page, choose Standard Create.
  • In the Configuration section, make the following changes:
    • For Engine type, choose Aurora (MySQL Compatible).

What is engine type?

The engine type is like the core software that powers our database. Imagine it as the operating system of a computer, but for databases.

๐Ÿ’ก Aha! So this is Aurora. How is it different to other databases?

AWS Aurora is a type of relational database. As you can tell from the first few steps of creating a relational database, there are plenty of options to choose from!

We'd use AWS Aurora if we needed something large-scale, with peak performance and uptime. This is because Aurora databases use clusters (more on that later!). Ordinary relational databases, like MySQL and Oracle are more generic and cost-effective. They suit smaller databases and less demanding workloads.

In summary; Aurora is for the big jobs.

Fun fact: Coca-Cola uses Amazon Aurora to store their consumer data globally!

  • For Engine Version, choose Aurora MySQL 3.08.2 (compatible with MySQL 8.0.39) - default for major version 8.0

What is Engine Version?

The engine version is like choosing the specific version of software that your database will use. For example, Aurora MySQL 3.05.2 (compatible with MySQL 8.0.32) is a specific version of Aurora that's compatible with a particular MySQL version (8.0.32).

  • For Templates, choose Dev/Test

What are Templates?

Templates are pre-set settings that help you quickly set up your database environment according to your needs. It's basically AWS helping you make selections for the rest of this set-up page! The Dev/Test template is designed for development and testing environments, helping you pick lower cost options.

  • In the Settings section, set these values:
    • DB cluster identifier: nextwork-db-cluster
    • Master username: admin
    • For Credentials management select Self managed.
    • Master password: Type a password (eg. n3xtw0rk)
    • Confirm password: Retype the password.
    • Make sure you save your database login details somewhere safe! You'll need them later on.
  • Leave the Cluster storage configuration settings as default.
  • In the Instance configuration section, set these values:
    • Burstable classes (includes t classes)
    • db.t3.medium
    • ๐Ÿšจ Update: Students have reported getting charged when they spend more than one hour with an active db.t3.medium instance. If you get stuck with any issues later in the project, ask the NextWork community .

What are Burstable classes?

The Burstable classes (includes t classess) are cost-effective types of database instances that are best when you have a consistent baseline level of traffic with occassional, random spikes in demand...a sudden "burst" of traffic. By choosing burstable classes, our database can perform well under high traffic, but also save us costs when things are quiet.

Extra for Experts: The other two DB instance classes are Serverless V2, which let you only pay for what you use (scales automatically from zero traffic), and memory optimized classes, which are designed for high-performance databases that need to do heavy, memory-intensive tasks.

  • In the Availability and durability section, use the default values. We'll jump into what this means later!
  • In the Connectivity section, the first thing it asks us is whether we need to connect to an EC2 instance...
  • For Compute resource, choose Connect to an EC2 compute resource.
  • Now select the drop down for EC2 instance, and choose nextwork-ec2-instance-web-server.
  • Scroll down and open the Additional configuration section.
  • Enter sample for Initial database name.
  • Keep the default settings for the other options.
  • Select Create database.

Did you notice some scary looking monthly costs?

Don't worry! As long as we delete our database as soon as we've finished with this project, we'll be absolutely fine. If you run into any issues you can always ask in the NextWork community

  • Close any pop-ups that appear.
  • Your new DB cluster will show in the Databases list with the status Creating.
  • Do you notice that your database has the name nextwork-db-cluster and that there's two of them? What's with that?

Note

It may take five or more minutes for the database to be created. Time for a tea and bit of an explanation โ˜•

What's this 'database cluster' business?

Remember how we said that Aurora is really good for the big jobs? The reason for this is clusters.

A database cluster in Aurora is a group of database copies that work together so your data is always available.

Each cluster consists of a primary instance (where all write operations occur) and multiple read replicas as back-ups. If your database's primary instance fails, one of the replicas can be promoted to primary automatically.

  • Wait for the Status of your new DB cluster to show as Available.
  • Select the DB identifier of your top database to take a look at the details.
  • Notice that there are two Endpoints in our Database. Cool! This is our cluster in action.

Understanding Reader vs Writer instances

Our writer database instance is our primary instance that handles all the "write" operations like INSERT, UPDATE, and DELETE.

Our reader database instance is our backup instance that can do very basic operations like SELECT. This is used to get data, but not to add or change data.

Why separate read and write?

We only want one writer instance at a time so that things stay focused and controlled...but we want multiple reader instances so that we can share the workload for read requests as our database grows and have a backup if our writer instance fails.

What is an endpoint?

In general, endpoints are like contact points where data flows in and out. A super popular example is a website URL! When you enter a website's address (like nextwork.org), your browser uses that endpoint to receive data and load the page. For databases, an endpoint is how your app finds a database to ask for data or update it.

  • Yay! We've created a new relational database and have a waiting EC2 instance for our beautiful new web app.

This is what we created in this step:

Create your web app

In this step, get ready to:

  • Connect to your EC2 instance through SSH.
  • Install a basic Web App that runs on your EC2 instance.

Open your local Terminal

  • On a Mac:
    • Press Cmd + Space to open Spotlight.
    • Type Terminal and press Enter.
  • On a Windows/Linux:
    • Press Windows + R to open the Run dialog.
    • Type cmd or powershell and press Enter.

Connect to your EC2 instance

  • You need to access your .pem file in order to login successfully to your EC2 instance - remember, the .pem file is like your keys to your EC2 instance!
  • Find your .pem file on your local computer (it's probably in your downloads folder!) and put it in a new folder on your Desktop labelled nextwork
  • Nice! Now we need to navigate to that folder from your terminal, so we can use it.
  • Run the command ls in your terminal - this shows you all the folders that you can see from your current terminal position.
  • If you can see the Desktop folder when you run ls then you're in the right place.
    • If you can't see the Desktop folder, then use the following commands to navigate up and down your folders until you can see Desktop...
    • To go back one folder run the command cd ../.
    • To go into a folder, run the command cd followed by the folder you'd like to enter (eg. cd nextwork or cd Desktop).

Note

If you're EVER stuck - ask the NextWork community. Students like you are already asking questions about this project.

  • Once you can see your Desktop folder, navigate into that folder by running cd Desktop.
  • Then navigate into your nextwork folder by running cd nextwork.
  • Run ls to make sure your .pem file is there!

Great! We have found our "keys" to get into our EC2 instance. Let's get inside!

  • Back in your terminal run the following command:
ssh -i NextWorkAuroraApp.pem ec2-user@[[EC2="YOUR_EC2_ADDRESS"]]
  • Whoops! Did you get an error telling you permissions denied?
  • That's because you need the right permissions to access your .pem file.
  • Try running this command if you're on Mac or Linux:
chmod 400 NextWorkAuroraApp.pem
  • Note: If chmod 400 doesn't work for you, ask the community! We have tips to share with you ๐Ÿ˜Š Hint: use Git Bash instead if you're on Windows.

Cool! How does that command give us access to our .pem file?

1. chmod stands for Change Mode. Itโ€™s a command used to change the permissions of a file or directory in Unix and Linux systems.

2. The 400 has a lot of meaning in it...

4 means "read-only" permission. The owner of the file can read the file but cannot write to it or execute it.

0 means "no permission." Neither the group nor others have any permissions (cannot read, write, or execute the file).

The order of these numbers also has meaning! The first digit represents the permission for the file owner, the second and third digits (0 and 0) represent the permissions for the group and others (everyone else).

So, 400 means the owner of the file can read it, but no one else (including the group or other users) can access it.

  • Once you've given your computer access to your .pem file, run the command to connect to our EC2 instance again:
ssh -i NextWorkAuroraApp.pem ec2-user@[[EC2="YOUR_EC2_ADDRESS"]]
  • Now remember that our EC2 instance is just another computer. First thing we need to do is make sure all the software on it is up to date!
  • Run the following command:
sudo dnf update -y

How does this command update our EC2 software?

๐Ÿฆธโ€โ™€๏ธ sudo means 'superuser do' and is like saying you have admin or root user rights.

๐Ÿ‘ท dnf is what is used to manage all the software on our EC2 instance.

โ˜๏ธ update tells 'dnf' to update all the software on the instance.

๐Ÿ‘ -y means automatically answer yes to any prompts that appear during the update process.

  • After the updates complete, we're going to install a whole bunch of stuff needed to run your web app. In particular...
    • an Apache web server - the most widely used web server in the world. A web server is a software that gets your content (e.g. web pages) to users via the internet.
    • PHP - a programming language used for writing beautiful app pages.
    • php-mysqli - a PHP library (i.e. a collection of pre-written code to help you save time) for establishing a MySQL connection to your database.
    • MariaDB - a relational database management system. Your Aurora database knows how to manage its data (e.g. how to add a new row or retrieve data), but your web server doesn't know how to send instructions to and understand the responses from your Aurora database. Your web server would need MySQL-compatible client libraries i.e. software designed for servers to communicate with a MySQL database. Installing MariaDB in your EC2 instance is one of the many ways to install these client libraries so it can interact with Aurora.
sudo dnf install -y httpd php php-mysqli mariadb105

What does this command do?

๐Ÿฆธโ€โ™€๏ธ sudo means 'superuser do' and is like saying you have admin or root user rights.

๐Ÿ‘ท dnf is what is used to manage all the software on our EC2 instance.

๐Ÿ‘‡ install tells 'dnf' that you want to install software on the instance.

๐Ÿ‘ -y means automatically answer yes to any prompts that appear during the update process.

๐Ÿ•ธ๏ธ httpd: installs the Apache HTTP Server package.

๐Ÿง‘โ€๐Ÿ’ป php: installs PHP.

๐Ÿ’ฌ php-mysqli: installs MySQL extension for PHP.

๐Ÿ  mariadb105: installs MariaDB, a version of the MySQL database management system.

  • All systems go! Let's start the most basic version of our web app with the following command:
sudo systemctl start httpd
  • Test that your web app is running by entering your IPv4 DNS address into your browser.
    • Make sure you change https to http - no 's'!
  http://[[EC2="YOUR_EC2_ADDRESS"]]

Nice! Now we have our app set up and we can access it via our terminal, we can connect it to our Aurora database.

Make your Web App Cool

We've got a working database, EC2 instance, and now a basic web app running. HUGE!

But we still haven't actually connected our web app with our database. Wouldn't it be cool if we could update and see the changes of our database from our web app?

Let's build it!

In this step, get ready to:

  • Create a new folder and file in your EC2 instance to connect to your Aurora database.
  • Add a PHP script to make a more user-friendly web page for your app.

Connect your EC2 instance to your Database

  • While still connected to your EC2 instance, navigate to the www folder (this is where we store all our files for our web app!).
cd /var/www
  • Create a new sub-folder named inc.
mkdir inc
  • Whoops! Did you get another permission denied error?
  • Let's find out what's going on here. Who actually has permissions in this folder? Run the following command to find out:
ls -ld

What does this do?

The command ls means list, and -ld means "list the details".

Does the details of your folder look like this?

This means that the root user is the owner of this folder, and only the owner can edit this folder. When you access an EC2 instance using a key pair, you're by default logging in as an admin user (called ec2-user) which is not the root user!

Let's change the owner of this folder so you (ec2-user) can edit it.

  • Let's navigate back to where we were at the start:
cd ../../
  • Run the following command:
sudo chown ec2-user:ec2-user /var/www

Note

This changes the owner of the folder to the ec2-user....us!

๐Ÿ‘จโ€๐Ÿš’ chown means "change the owner permissions".

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ ec2-user:ec2-user means we change the individual and group user from root to ec2-user.

  • Now let's see the details of that folder again...
ls -ld var/www

Let's try it again.

  • Navigate to your www folder
cd /var/www
  • Create a new sub-folder named inc.
mkdir inc
  • Woohoo! No errors! Navigate into your new inc folder
cd inc
  • Create a new file in the inc directory named dbinfo.inc
>dbinfo.inc
  • Cool! Now we have a blank file. We can edit our new file by calling nano.
nano dbinfo.inc

Whoa! This looks freaky. What's going on?

Nano is a way we can edit files in the terminal. It looks a bit different, but it's nothing to be scared of!

We've just opened our blank dbinfo.inc file, and now we're going to add some code that connects it to our AWS database.

Extra for Experts: If you're still wondering what is Nano, Nano is a text editor that's designed to run entirely within the terminal window. Nano is a software that usually comes pre-installed in Linux and Unix systems e.g. this EC2 instance. But you'd have to install it manually if you'd like to use it in your local Windows computer's terminal!

  • dbinfo.inc is a settings file that stores the connection details our EC2 instance will need to connect to our Aurora database. To complete this file, we need our Aurora database endpoint.
  • Navigate to your Aurora database details in AWS and note the Endpoint of your Writer instance:
    • YOUR_WRITER_ENDPOINT
  • Copy and paste the following code to connect our EC2 instance to our Aurora database to the dbinfo.inc file.
    • If you've set up your user with a password other than n3xtw0rk, make sure to update DB_PASSWORD too.
<?php

define('DB_SERVER', '[[ENDPOINT="YOUR_WRITER_ENDPOINT"]]');
define('DB_USERNAME', 'admin');
define('DB_PASSWORD', 'n3xtw0rk');
define('DB_DATABASE', 'sample');
?>

Note

Notice that these details are all from when you first set up your Aurora database! Cool!

  • Save and close the dbinfo.inc file by using Ctrl+S to save and then Ctrl+X to exit.

Nice! Now that our database is all connected, let's upgrade our web app page.

Upgrade your Web App

  • Navigate to your html folder:
cd /var/www/html
  • Create a new file in the html directory named SamplePage.php, and then edit the file by calling nano
>SamplePage.php
nano SamplePage.php
  • Copy and paste the following script into your SamplePage.php file:
<?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;
}
?>                        

Wow - that's one big block of code! What does THIS one do?

This big block of code is what makes our new web app look so cool! It's pulling in the details from our dbinfo.inc file we created earlier and using it to display up-to-date changes directly from our website. SO COOL!

If you're feeling adventurous, you can customise this page to make the styling how you like it.

  • Save and close the SamplePage.php file by using Ctrl+S to save and then Ctrl+X to exit.

If you get another Permission Denied error, you know what to do!

1. Exit nano by choosing Ctrl+X.

2. Run ls -ld to check who is the owner of this folder

3. Update the owner to you by running sudo chown ec2-user:ec2-user .

4. Try pasting and saving your SamplePage.php file again.

  • Verify that your web server successfully connects to your DB cluster by opening a web browser and browsing to
http://[[EC2="YOUR_EC2_ADDRESS"]]/SamplePage.php

Check that it worked!

In this step, get ready to:

  • Test your new web app in the browser
  • Check that it is correctly updating your Aurora database by using MySQL CLI
  • In your browser, where your new web app is running, add some new data.
  • Notice how your results show on the page? If you're wondering how that happens, go back and have a look at your SamplePage.php file. All the magic is there!

But is this actually updating our Aurora database? ๐Ÿค” Let's check!

Connect to your Database using MySQL CLI

To access your database, you're going to use MySQL.

Note

MySQL CLI is a powerful, secure, and efficient tool for interacting with MySQL databases. It provides direct access to all MySQL features, supports automation, and is a preferred method for managing databases on remote servers, such as EC2 instances.

  • Download the MySQL repository into your EC2 instance:
sudo yum install https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm -y
  • Install MySQL:
sudo yum install mysql-community-client -y
  • Connect to your Aurora MySQL Database:
mysql -h [[ENDPOINT="YOUR_WRITER_ENDPOINT"]] -P 3306 -u admin -p
  • Make sure you replace:
    • YOUR_ENDPOINT with the Endpoint from your Aurora Writer instance
    • YOUR_PORT with the Port from your Aurora Writer instance; 3306
    • YOUR_AURORA_USERNAME with your Aurora username; admin
  • Enter in your Aurora password when prompted; n3xtw0rk
  • Run SHOW DATABASES;
    • This shows you the databases that are in your MYSQL server.
  • Run USE sample;
    • sample is the name you gave your first database schema.
  • Run SHOW TABLES;
    • This shows you the tables in your sample schema.
    • If you're wondering where Employees came from, check your SamplePage.php file. It's all there! (Hint: this is also where you can change it if you're feeling creative)
  • Run DESCRIBE EMPLOYEES;
    • This tells you how the Employees table is structured.
  • Run SELECT * FROM EMPLOYEES;
    • This shows you the actual data in your table!
  • Now it's over to you! Have a play around adding more data in your web app, then re-running the commands above to check the data in your database.

Delete Your Resources

Delete Your Resources

Make sure you delete all your resources to avoid getting charged. This is a super important task for every single project you set up. Don't keep your resources in your account if you'll wait to come back to this series on another day.

Important

Deleting resources that are not actively being used stops you getting charged and is a best practice. Not deleting your resources will result in charges to your account.

Do you think you can delete the resources you've created today?

Yep, of course.

  • The database cluster
  • The EC2 instance
  • The key-pair

I know, but also, I don't...

If you're feeling stuck (we've all been there!), here's a little guide:

  • The database cluster
  • Open the Amazon RDS console, select Databases.
  • Choose nextwork-db-cluster.
  • From the Actions drop-down menu, choose Delete.
    • ๐Ÿšจ When deleting your database cluster, make sure to uncheck Create final snapshot and uncheck Retain automated backups so you don't get charged.
  • The EC2 instance
  • Open the Amazon EC2 console, select Instances.
  • Choose the instance you created.
  • Click Actions at the top, then Terminate instance.
  • The key-pair
  • Open the Amazon EC2 console, select Key Pairs.
  • Choose the key pair you created.
  • Click Actions at the top, then Delete Key Pair.

Nice Work!

Nice Work!

Woohooooo!! You are an absolute legend and should be very proud of yourself. That was not easy work but you gave it a go, did your best, and absolutely crushed it.

Today you've learnt how to:

  • ๐Ÿงฑ Create an Aurora MySQL Database: You created an Aurora MySQL database instance from scratch in AWS, configured it with the appropriate settings, and connected it to an EC2 instance to prepare for hosting a web application.
  • ๐Ÿ’ป Launch and Configure an EC2 Instance: You successfully launched an EC2 instance using the Amazon Linux 2023 AMI, configured the instance to connect to your Aurora database, and set up the necessary security groups to allow traffic.
  • ๐ŸŒ Build and Connect a Web Application: You built a basic web application on your EC2 instance, connected it to your Aurora MySQL database, and used PHP and MySQLi to interact with your database through a web interface.
  • ๐Ÿ”— Test and Verify Database Interactions: You verified that your web application successfully connected to your Aurora MySQL database by running SQL queries, viewing data through the web app, and confirming changes directly in the database using the MySQL CLI.

Ready to quiz yourself? You got this! ๐Ÿ’ช

It's wild that all these learnings are packed in one project. Great work and we'll see you in the next database project, Load Data into DynamoDB!

p.s. Does it say "Still tasks to complete!" at the bottom of the screen?

This means you still have screenshots left to upload, or questions left to answer!

  1. Press Ctrl+F (Windows) or Command+F (Mac) on your keyboard.
  2. Search for the text Return to later.
  3. Jump straight to your incomplete tasks!
  4. ๐Ÿ™‹โ€โ™€๏ธ Still stuck? Ask the community!