DEV Community

Cover image for POC: Three-Tier Architecture on AWS with RDS, Flask Microservice, and PHP Frontend
Indika_Wimalasuriya
Indika_Wimalasuriya

Posted on

POC: Three-Tier Architecture on AWS with RDS, Flask Microservice, and PHP Frontend

In today's fast-paced digital landscape, building scalable and efficient architectures is paramount for successful application development. One such approach is the Three-Tier Architecture, which separates an application into three distinct layers: the presentation layer, the application layer, and the data storage layer. Each layer has its own responsibilities, promoting modularity, flexibility, and ease of maintenance. In this blog post, we will delve into creating a Proof of Concept (POC) for implementing a Three-Tier Architecture on Amazon Web Services (AWS) using key services such as Amazon RDS, Flask Microservice, and PHP frontend.

High level design

The journey begins with setting up the AWS RDS database, where we will create a MySQL database to store employee information. We will then connect to this database from an EC2 instance to interact with the data and execute SQL queries. Next, we will build a Python program to read data from the RDS database, ensuring seamless connectivity between our backend and the database.

The heart of our architecture lies in the Flask Microservice, which will serve as the application layer. We will develop a RESTful API with Flask, enabling communication between the frontend and the backend. The Flask Microservice will retrieve employee data from the RDS database and present it in a structured JSON format.

On the frontend side, we will set up a PHP server on another EC2 instance to create a simple web page. Using PHP, we will communicate with the Flask Microservice to retrieve employee data and display it on the webpage. This demonstrates the seamless interaction between the frontend and the backend, highlighting the power of Three-Tier Architecture.

Step 1: Setting up the Database on AWS RDS

Log in to your AWS console and navigate to RDS.

Create a new database and select "Easy Create."
Choose the MySQL engine for simplicity.
Configure the database settings:
DB instance Identifier: [masked]
Master Username: [masked]
Master Password: [masked]

Note: Keep in mind that some RDS instances may not have a public IP address, and only resources within the VPC can access them.

Step 2: Connect to the RDS Database from an EC2 Instance

To interact with the RDS database from an EC2 instance, install the MySQL client and establish the connection:

sudo yum install -y mysql-community-client --nogpgcheck
mysql --version
mysql -h [masked] -u [masked] -p [masked]
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the POC Database and Table

Now, let's create the database and table to store employee information:

CREATE DATABASE pocdb;
USE pocdb;

CREATE TABLE employee (
    employee_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);

INSERT INTO employee (name) VALUES ('John Doe'), ('Jane Smith');

Enter fullscreen mode Exit fullscreen mode

Step 4: Building a Python Program to Read Data from RDS

Create a Python program on the EC2 instance to read data from the RDS database:

import mysql.connector

def read_employee_data():
    # RDS database connection details (masked)
    host = "[masked]"
    user = "[masked]"
    password = "[masked]"
    database = "pocdb"

    try:
        # Establish a connection to the MySQL database
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )

        if connection.is_connected():
            print("Connected to the database.")
            cursor = connection.cursor()

            # Define the SQL query to retrieve all data from the employee table
            sql_query = "SELECT * FROM employee"

            # Execute the query
            cursor.execute(sql_query)

            # Fetch all rows from the result set
            rows = cursor.fetchall()

            # Process the result set and print the data
            for row in rows:
                employee_id = row[0]
                name = row[1]
                print(f"Employee ID: {employee_id}, Name: {name}")

            # Close the cursor and connection
            cursor.close()
            connection.close()
        else:
            print("Database connection failed.")

    except mysql.connector.Error as e:
        print(f"Error connecting to the database: {e}")

if __name__ == "__main__":
    read_employee_data()

Enter fullscreen mode Exit fullscreen mode

Please test the program to ensure that data retrieval from the database in standalone mode is functioning properly.

Step 5: Creating the Flask Microservice on the EC2 Instance

Install Flask on the EC2 instance and set up a Flask microservice to retrieve employee data from the RDS database:

pip install Flask

Enter fullscreen mode Exit fullscreen mode
from flask import Flask, jsonify
import mysql.connector

app = Flask(__name__)

@app.route('/employees', methods=['GET'])
def get_employees():
    # RDS database connection details (masked)
    host = "[masked]"
    user = "[masked]"
    password = "[masked]"
    database = "pocdb"

    try:
        # Establish a connection to the MySQL database
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )

        if connection.is_connected():
            cursor = connection.cursor()

            # Define the SQL query to retrieve all data from the employee table
            sql_query = "SELECT * FROM employee"

            # Execute the query
            cursor.execute(sql_query)

            # Fetch all rows from the result set
            rows = cursor.fetchall()

            # Close the cursor and connection
            cursor.close()
            connection.close()

            # Process the result set and build a list of employees
            employees = []
            for row in rows:
                employee_id = row[0]
                name = row[1]
                employee_data = {"employee_id": employee_id, "name": name}
                employees.append(employee_data)

            # Return the list of employees as JSON response
            return jsonify(employees)
        else:
            return "Database connection failed.", 500

    except mysql.connector.Error as e:
        return f"Error connecting to the database: {e}", 500

if __name__ == "__main__":
    app.run(host='172.31.95.155', port=5000)

Enter fullscreen mode Exit fullscreen mode

Step 6: Testing the Flask Microservice

Start the Flask microservice on the EC2 instance and test its functionality:

python3 Microservice.py

Enter fullscreen mode Exit fullscreen mode
curl http://[Masked]:5000/employees

Enter fullscreen mode Exit fullscreen mode

Step 7: Setting up the Frontend PHP Server

On another EC2 instance, install PHP and configure a simple PHP script:

sudo yum update
sudo yum install php
sudo service httpd start
sudo mv hello.php /var/www/html/
sudo chown apache:apache /var/www/html/hello.php

Enter fullscreen mode Exit fullscreen mode

hello.php:

<?php echo 'Hello, World!'; ?>

Enter fullscreen mode Exit fullscreen mode

*Step 8: Testing the PHP Frontend
*

Test the PHP frontend by accessing the PHP file:

http://[masked]/hello.php

Enter fullscreen mode Exit fullscreen mode

Step 9: Using PHP to Retrieve Data from the Flask Microservice

Modify the PHP script to retrieve employee data from the Flask microservice:

<?php
// Replace the API endpoint with the correct URL of your microservice
$apiUrl = 'http://[Masked]:5000/employees';

// Make an HTTP GET request to the API endpoint
$response = file_get_contents($apiUrl);

// Check if the response is valid
if ($response === false) {
    echo "Error fetching data from the microservice.";
} else {
    // Decode the JSON response into an associative array
    $data = json_decode($response, true);

    // Check if the JSON decoding was successful
    if ($data === null) {
        echo "Error decoding JSON data from the microservice.";
    } else {
        // Loop through the data and display the employee information
        echo "<h1>Employee List</h1>";
        echo "<ul>";
        foreach ($data as $employee) {
            echo "<li>Employee ID: " . $employee['employee_id'] . ", Name: " . $employee['name'] . "</li>";
        }
        echo "</ul>";
    }
}
?>

Enter fullscreen mode Exit fullscreen mode

Step 10: Final Testing and Conclusion

Access the PHP script again to see the retrieved employee data from the Flask microservice.

This blog post showcased the implementation of a Three-Tier Architecture on AWS, combining Amazon RDS, Flask Microservice, and PHP frontend. By separating the application into distinct layers, the architecture offers modularity, scalability, and maintainability. The RDS database stored employee information, the Flask Microservice served as the application layer, and PHP interacted with the backend to display data on a web page. The seamless integration between these layers exemplifies the potential of Three-Tier Architecture in building robust and scalable applications

Top comments (0)