How to Deploy a Flask App to AWS Elastic Beanstalk

AWS

YOUR COSMETIC CARE STARTS HERE

Find the Best Cosmetic Hospitals

Trusted • Curated • Easy

Looking for the right place for a cosmetic procedure? Explore top cosmetic hospitals in one place and choose with confidence.

“Small steps lead to big changes — today is a perfect day to begin.”

Explore Cosmetic Hospitals Compare hospitals, services & options quickly.

✓ Shortlist providers • ✓ Review options • ✓ Take the next step with confidence

AWS Elastic Beanstalk and Flask complement each other well: Flask lets you build a Python web application quickly, and Elastic Beanstalk handles the underlying AWS infrastructure automatically. This tutorial walks through the entire workflow — from local setup to deployment to teardown.

What Is AWS Elastic Beanstalk?

Elastic Beanstalk is a Platform-as-a-Service (PaaS) offering from AWS. When you upload your application code, Elastic Beanstalk automatically provisions and manages the underlying resources — EC2 instances, Elastic Load Balancers, Auto Scaling groups, CloudWatch alarms, and S3 buckets — so you don’t have to configure each service individually.

Supported platforms include Python, Java, Node.js, Ruby, .NET, PHP, Go, and Docker, running on servers such as Apache, Nginx, Passenger, and IIS. When the application is no longer needed, you can tear down all associated resources in a single command rather than deleting each AWS resource by hand.

What Is Flask?

Flask is a lightweight Python web microframework. It has minimal dependencies and a simple API, making it a popular choice for small web services, REST APIs, and prototypes. In this tutorial, we use Flask to build a minimal application that serves a single HTML page.

Prerequisites

Before you begin, make sure the following tools are installed on your local machine:

  • Python — The tutorial was originally written for Python 2.7. Python 2 is end-of-life; consider using Python 3 and adjusting the eb init platform flag accordingly (e.g., python-3.8).
  • pip — The Python package manager, used to install dependencies and generate requirements.txt.
  • virtualenv — Creates an isolated Python environment so that only the packages your application needs are deployed.
  • awsebcli — The Elastic Beanstalk command-line interface, used to initialise, create, deploy, and terminate Elastic Beanstalk environments.
  • An AWS account with sufficient IAM permissions to create Elastic Beanstalk environments and the resources they depend on.

Install the tools with the following commands:

sudo apt install python3-pip
pip install virtualenv
pip install awsebcli

Step 1 — Set Up a Python Virtual Environment

Create a dedicated project directory, move into it, and initialise a virtual environment. Activating the environment ensures that any packages you install are scoped to this project and will be accurately captured in requirements.txt.

mkdir myflaskapp
cd myflaskapp
virtualenv venv
source venv/bin/activate

Once the virtual environment is active, your prompt will be prefixed with (venv). Now install Flask and freeze the dependency list:

pip install flask
pip freeze > requirements.txtCode language: CSS (css)

Elastic Beanstalk reads requirements.txt to determine which packages to install in the deployment environment. Without this file, your application will fail to start on the platform.

Step 2 — Create the Flask Application

Elastic Beanstalk for Python looks for a callable named application (not app) inside a file named application.py. This naming convention is mandatory — if you use a different name, the platform will not find your WSGI entry point.

Create application.py with the following content:

from flask import Flask

html = """
<html>
  <head><title>My Flask Application</title></head>
  <body>
    <h1>This is the Home page!</h1>
  </body>
</html>
"""

application = Flask(__name__)

@application.route('/')
def index():
    return html

if __name__ == "__main__":
    application.debug = True
    application.run()Code language: HTML, XML (xml)

Test it locally before deploying:

python application.pyCode language: CSS (css)

Flask will serve the page at http://127.0.0.1:5000 by default. Open that URL in a browser to verify the page loads correctly.

Step 3 — Exclude the Virtual Environment from Deployment

Your project directory should now contain:

myflaskapp/
├── application.py
├── requirements.txt
└── venv/          <-- do NOT deploy thisCode language: PHP (php)

The venv/ directory should not be uploaded to Elastic Beanstalk — it is large and platform-specific. Create an .ebignore file to tell the EB CLI to skip it:

echo "venv/" > .ebignoreCode language: PHP (php)

The .ebignore file follows the same syntax as .gitignore. If your project already has a .gitignore, the EB CLI will use it unless an .ebignore file is present.

Step 4 — Initialise the Elastic Beanstalk Application

Use the EB CLI to initialise a new Elastic Beanstalk application. The -p flag specifies the platform and the --region flag sets the AWS region.

eb init myflaskapp -p python-3.8 --region us-east-1Code language: CSS (css)

The CLI will prompt you for your AWS access key and secret key if they have not already been configured via the AWS CLI or environment variables. It will also ask whether you want to set up SSH access for the EC2 instances (optional for a basic deployment).

This command creates a hidden .elasticbeanstalk/ directory in your project folder containing configuration metadata. It does not yet create any AWS resources.

Step 5 — Create the Elastic Beanstalk Environment and Deploy

Create a named environment and deploy your source code to it:

eb create myflaskappenv

Elastic Beanstalk will now:

  1. Package your source code into a ZIP archive and upload it to S3.
  2. Provision an EC2 instance (or instances) running the Python platform.
  3. Create a security group, an Elastic Load Balancer, and an Auto Scaling group.
  4. Install dependencies from requirements.txt and start your application.

This process takes a few minutes. The EB CLI streams event log output to your terminal so you can follow progress. When it completes successfully, the environment health should show as Green in the Elastic Beanstalk console.

Step 6 — Test the Deployed Application

Open the live application directly from the CLI:

eb open

This command resolves the environment’s public URL and opens it in your default browser. You should see the same HTML page you tested locally.

You can also verify the response from the command line using curl. Replace the URL with the one shown in your Elastic Beanstalk console:

curl http://myflaskappenv.<region>.elasticbeanstalk.com/Code language: HTML, XML (xml)

A correct response returns the HTML content of the index page with an HTTP 200 status.

Step 7 — Update the Application

After the initial deployment, you can modify your source code and push an updated version to Elastic Beanstalk with a single command:

eb deploy

Elastic Beanstalk packages the new code, uploads it to S3 as a new application version, and performs a rolling update of the environment. Previous application versions are retained in S3 and in the Elastic Beanstalk console, so you can roll back if needed.

Step 8 — Tear Down the Environment

When you no longer need the application, terminate the environment to stop incurring AWS charges. The eb terminate command deletes the environment and all the AWS resources it provisioned — EC2 instances, load balancers, Auto Scaling groups, CloudWatch alarms, and the associated security group:

eb terminate myflaskappenv

The CLI will ask you to confirm before deleting resources. The S3 bucket storing application versions and the Elastic Beanstalk application record itself are not deleted by default; you can remove them manually from the AWS console or with additional CLI flags if needed.

Key Takeaways

  • Name your WSGI entry point application.py and your Flask instance application — this is required by the Elastic Beanstalk Python platform.
  • Always generate and commit requirements.txt so the platform can reproduce your dependencies.
  • Use .ebignore to exclude the local virtual environment from the deployment bundle.
  • The full lifecycle — create, deploy, update, terminate — can be managed entirely from the EB CLI without logging into the AWS console.
  • Consider using Python 3 and a current platform version for any new projects, as Python 2 reached end-of-life in January 2020.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x