How to Host Python Web App on AWS EC2

Hosting a Python web application on AWS EC2 with a MySQL database is an ideal solution for small to medium-sized applications. EC2 provides flexible virtual servers, allowing you to scale up or down as needed. In this blog, we’ll go step-by-step through deploying a Python web application using EC2 with a MySQL database.

mitron global blog

Contents

  1. Setting Up AWS EC2 for Python Hosting
  2. Configuring Security Groups for Access
  3. Installing Python and Required Libraries
  4. Setting Up and Configuring MySQL on EC2
  5. Deploying the Python Web Application
  6. Connecting Python App with MySQL
  7. Testing and Securing Your Application

1. Setting Up AWS EC2 for Python Hosting

Step 1: Log into AWS and Launch an EC2 Instance

  1. Sign into your AWS Management Console.
  2. Navigate to EC2 Dashboard and click Launch Instance.
  3. Choose an Amazon Machine Image (AMI). The Amazon Linux 2 AMI is recommended due to its compatibility and ease of use.
  4. Select an instance type, such as t2.micro (eligible for free tier).
  5. Configure the instance settings, storage, and tags as per your needs.
  6. In the Security Group section, create a new group or use an existing one, and make sure to allow HTTP, HTTPS, and SSH access (we’ll cover this in detail in the next section).
  7. Review and launch the instance. Download the private key .pem file for SSH access.

Step 2: Access the Instance via SSH

  1. Open a terminal and navigate to the directory where your .pem file is saved.
  2. Use the following command to connect, replacing your-key.pem with your actual key file and ec2-user with your EC2 user:
ssh -i "your-key.pem" ec2-user@your-ec2-public-ip

2. Configuring Security Groups for Access

  1. In the Security Group settings for your instance:
    • Add an SSH rule on port 22 (source can be your IP for security).
    • Add HTTP and HTTPS rules on ports 80 and 443 (source can be 0.0.0.0/0 for public access).
    • Add a custom TCP rule to allow MySQL on port 3306 (restrict source to specific IPs or your internal IP range).
  2. Save changes. These rules will allow you to access your application through HTTP/HTTPS, SSH into the instance, and access the MySQL database remotely if needed.

3. Installing Python and Required Libraries

Once logged into the instance:

  1. Update system packages:
sudo yum update -y
  1. Install Python (Amazon Linux usually comes with Python installed, but you can install a specific version):
sudo yum install python3 -y
  1. Set up a virtual environment for your project and activate it:
python3 -m venv myenv
source myenv/bin/activate
  1. Install application dependencies, including Flask (or Django if you’re using it):
pip install flask pymysql
  1. Optionally, create a requirements.txt file to document dependencies
pip freeze > requirements.txt

4. Setting Up and Configuring MySQL on EC2

Option 1: Installing MySQL on the Same EC2 Instance

  1. Install MySQL server:
sudo yum install mysql-server -y
  1. Start the MySQL service:
sudo service mysqld start
  1. Secure MySQL installation by setting a root password:
sudo mysql_secure_installation
  1. Create a new database and user for your application:
mysql -u root -p
CREATE DATABASE myappdb;

CREATE USER 'myappuser'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON myappdb.* TO 'myappuser'@'localhost';

FLUSH PRIVILEGES;

EXIT;

Option 2: Using Amazon RDS for MySQL

You can also set up a separate MySQL instance using Amazon RDS, which manages the database for you and integrates easily with your EC2 instance.

5. Deploying the Python Web Application

  1. Copy your application files to the EC2 instance, either by SCP or Git.
scp -i "your-key.pem" -r /path/to/your/app ec2-user@your-ec2-public-ip:/home/ec2-user/
  1. Set up a simple Flask app. Here’s an example app.py file:
from flask import Flask

import pymysql

app = Flask(__name__)

@app.route('/')

def home():

    return "Hello, World! Your app is running!"

if __name__ == '__main__':

    app.run(host='0.0.0.0', port=80)
  1. Run your application:
sudo python3 app.py

To keep your app running, consider using a process manager like Gunicorn for production, or configure Nginx to serve the app as a reverse proxy.

6. Connecting Python App with MySQL

Update your application to connect to MySQL. Here’s an example of how to do it in Flask:

import pymysql

# Connect to database

db = pymysql.connect(

   host="localhost",

   user="myappuser",

   password="password",

   database="myappdb"

)

@app.route('/data')

def get_data():

   with db.cursor() as cursor:

       cursor.execute("SELECT * FROM your_table")

       results = cursor.fetchall()

       return {"data": results}

Be sure to replace placeholders with your actual database and table names. Also, handle any potential database connection errors.

mitron global blog

7. Testing and Securing Your Application

Testing

  1. Open a web browser and enter your EC2 instance’s public IP. You should see your app’s landing page (e.g., “Hello, World! Your app is running!”).
  2. Test other routes to ensure the MySQL connection and data retrieval work as expected.

Securing Your Application

  1. Set up HTTPS with a tool like Let’s Encrypt to ensure encrypted connections to your application.
  2. Use environment variables to store sensitive data such as database passwords.
  3. Enable firewall rules to limit access to specific IPs for MySQL.
  4. Regularly update your instance, application, and dependencies to avoid vulnerabilities.

Conclusion

Hosting a Python web application with MySQL on AWS EC2 is an accessible and flexible way to deploy and scale your projects. Following these steps, you’ve set up an EC2 instance, configured MySQL, and deployed a Python app connecting to a database. With a secure and well-tested deployment, your application is ready for real-world usage!

You can also setup with advanced tools like Docker for containerization or CI/CD pipelines for easier updates. AWS also provides scalable options if you need to add more resources to handle increased traffic in the future. Happy deploying!

Click here for more

Scroll to Top