How to deploy Flask app on AWS EC2
To deploy our application, we must configure our EC2 instance before connecting. After establishing the connection with the EC2 instance, we must set up the environment to run the Flask application. We will start by configuring our EC2 instance.
Deploy an EC2 instance
We will start by creating a security group. We need the virtual private cloud ID to configure the security group. We will be using an already existing VPC. The command to get the existing VPCs is as follows:
aws ec2 describe-vpcs --query 'Vpcs[*].VpcId'
The command to create a security group is as follows:
aws ec2 create-security-group --group-name flask-sg --description "Security group to establish ssh connection with the EC2 instance" --vpc-id <VPC_ID>
The
create-security-grouptag creates the security group.The
--group-nametag sets the name of our security group.flask-sgis the name of the security group that we are creating.The
--descriptiontag sets the description for the security group.The
--vpc-idtag specifies the virtual private cloud in which the system would reside. Replace<VPC_ID>placeholder with the VPC ID that we retrieved using the previous command.
Note: After the security group is created, we will receive a
group-idwe need to save thisgroup-idfor later stages.
Allow SSH connection with the EC2 instance
To establish a connection with the EC2 instance, it is necessary that we modify the security group to allow an SSH connection. We can achieve that by the following command:
aws ec2 authorize-security-group-ingress --group-id <Security Group ID> --protocol tcp --port 22 --cidr 0.0.0.0/0
authorize-security-group-ingress: Modifies the inbound (ingress) rules of a security group.--group-id: Specifies the ID of the security group for which we want to add the inbound rule.<Security Group ID>: Replace this with the security group ID.--protocol: Specifies the network protocol, and we usetcpas our protocol to establish SSH.--port: Specifies the port to allow the traffic, and for SSH connection, we use22.--cidr: Specifies the IP range from which the incoming traffic is allowed.0.0.0.0/0means that traffic from any IP range is allowed.
Similarly, we can configure HTTPS and HTTP connection to our EC2 instance by the following commands:
aws ec2 authorize-security-group-ingress --group-id <Security Group ID> --protocol tcp --port 443 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id <Security Group ID> --protocol tcp --port 80 --cidr 0.0.0.0/0
To access our application directly from the public IP address, we need to allow traffic on the respective port in our security group. We will deploy our Flask application on port 5000. The command to allow traffic on port 5000 is as follows:
aws ec2 authorize-security-group-ingress --group-id <Security Group ID> --protocol tcp --port 5000 --cidr 0.0.0.0/0
Configure the EC2 instance
We need to generate the key pair to configure a secure connection with the EC2 instance. The command to generate the key pair is:
aws ec2 create-key-pair --key-name Flask-key-pair --query 'KeyMaterial' --output text > key.pem
create-key-pairis required to generate the key pair.The
--key-nametag sets the name of the key pair toFlask-key-pair(we can name it whatever we want).The
--query 'KeyMaterial' --output textpart of the command extracts the key material and outputs it as plain text.The
> key.pempart saves the output to a file named “key.pem.”
Note: Save the contents of the key on some local storage i.e a text file so that we don't loose it. We can display the contents of
key.pemby the commandcat key.pem. If the session times out we can create akey.pemfile using thetouchcommand and paste the contents there by either usingnanoorcat >> key.pemcommand.
Create the EC2 instance
The command to create the EC2 instance is:
aws ec2 run-instances --image-id ami-053b0d53c279acc90 --instance-type t2.micro --key-name Flask-key-pair --security-group-ids <Security Group ID>
aws ec2 run-instancesis the command to launch EC2 instances.--image-idspecifies the Amazon Machine Image (AMI) to use for the EC2 instance.ami-053b0d53c279acc90is the ami-id for the Ubuntu image. We can replace it with the latest ID available or the preferred base image.--instance-type t2.microspecifies the instance type for the EC2 instance.t2.microis one of the smallest and most cost-effective instance types, and it is suitable for low to moderate workloads.--key-namespecifies the key pair used for secure SSH connection to the EC2 instance.Flask-key-pairis the name of key pair that we generated above and stored inkey.pemfile.--security-group-idsspecifies the security group associated with the instance. Replace<Security Group ID>with our security group ID.
We need to give the key.pem file read permission. Use the following command to give key.pem read permissions:
chmod 400 key.pem
Note: After the EC2 instance is created, save the instance id.
Connection with EC2 instance from shell
We can connect to our EC2 instance using the public IP address. We can get the public IP address of the EC2 instance by the following command:
aws ec2 describe-instances --instance-ids <EC2 instance ID> --query 'Reservations[*].Instances[*].PublicIpAddress' --output text
Replace <EC2 instance id> with the instance ID that we saved earlier.
Now, we can connect to the EC2 instance using the following command:
ssh -i key.pem ubuntu@<PublicIpAddress>
Replace <PublicIpAddress> with the public IP address of the EC2 instance.
Configure the environment for the Flask application
After connecting to the EC2 instance, we can configure the environment by using the following commands:
Install python virtual environment.
sudo apt-get update && sudo apt-get install python3-venv
Create a new directory and navigate to that directory.
mkdir SampleProject && cd SampleProject
Create a virtual environment for the application.
python3 -m venv virenv
Activate the virtual environment.
source virenv/bin/activate
Install Flask to run the Flask application.
pip install Flask
Edit
app.pyto add the code to be executed.
sudo vi app.py
Implement the code for the application.
from flask import Flaskapp = Flask(__name__)@app.route('/')def Landing_page():return 'Hello Learners, Welcome to Educative!'if __name__ == "__main__":app.run(host='0.0.0.0', port=5000)
Note: To edit and save a file in
vieditor, enter the insert mode by pressing "i" and make modifications. Once done, exit the editor by pressing the "esc" key and typing ":wq!".
Run the Flask application.
python app.py
Practice
Run the commands given above in the following widget. Enter the AWS Access_Key_ID, Default_Region_Name and Secret_Access_Key in the widget below before running any commands.
The application can be accessed on <public ip address>:5000.
Free Resources