Data Science

AWS: Deploy FastApi apps on EC2 in minutes

AWS is a popular cloud provider that enables deployment and scaling of large applications. Mastering at least one cloud platform is an important skill for software engineers and data scientists. Running the application locally is not enough to make it available in production – it must be deployed on the server for access by the end user.

In this tutorial, we will introduce examples of deploying FastAPI applications. Although this example focuses on the core EC2 network concept, the principles are also widely applicable to other types of applications.

Note that this tutorial does not cover best practices for AWS usage. Instead, the goal is to provide readers with hands-on introduction to application deployment using EC2 instances.

#01. Instance creation

Navigate to the EC2 dashboard in the AWS Services menu and select Create a new instance. This will open a page that defines the instance parameters.

Select the corresponding instance type. In this tutorial, we will start a very simple server with minimal technical requirements, so t3.nano It should be enough to meet our needs.

For its containers, AWS uses SSH authentication. When creating a new instance, it is necessary to create a new key pair that will allow us to log in from the local computer using the SSH protocol. Click Create a new key pair.

Assign the name to the new key. We won’t sneak in the possible options here, so we’ll choose RSA as the key pair type and PEM as the private key file format.

To save time, we don’t have to worry about security in our demo application. For network settings, check all check boxes corresponding to SSH, HTTP, and HTTPS traffic.

Great! By clicking Start the instanceAWS will create a new instance.

After creating the instance, .pem The file will be downloaded to your local computer. This file contains the private key that allows SSH authentication. As a good practice, store this file in a secure location, as AWS does not provide a lost method to recover the file.

By opening the EC2 dashboard, you will notice that the created instance has the associated IP address. This IP is displayed under the tag “Public IPv4 Address”. For example, in the following image, it is “16.16.202.153”. After the application is deployed, it will be accessed from the browser using this IP address.

#02. ssh connection

AWS provides multiple methods to perform authentication. In our case, we will use the SSH mechanism.

In the instance menu, click connect And choose SSH Client From top bars.

Open the local terminal and use the screenshot above as a reference, copy and execute command #3 (chmod 400 ".pem") and the commands shown below “example” Label. Make sure your current terminal directory is .pem The key has been downloaded in the previous step.

During an SSH connection, the terminal may prompt whether to continue. If so, enter “Yes”.

At this point, we have successfully connected to the EC2 instance from the local terminal. Now any commands entered will be executed directly in the EC2 container.

#03. Environment configuration

After connecting to the instance from a local terminal, the next step is to update the package manager and install Python with Nginx.

sudo apt-get update
sudo apt install -y python3-pip nginx

To redirect traffic to our application, we need to create a nginx configuration file. The file should be placed in the directory /etc/nginx/sites-enabled/ And can have any custom name. We will add the following configuration:

server {
  listen 80;
  server_name ;
  location / {
    proxy_pass 
  }
}

Basically, what we specify is that any external request to the IP address of the EC2 instance on default port 80 should be redirected through the proxy application running inside the EC2 container running on the address http://127.0.0.1:8000. As a reminder, this is the default HTTP address and port assigned by FastApi.

To apply these changes, we need to restart NGINX:

sudo service nginx restart

If we have a FastAPI server to start, the easiest way is to publish it on GitHub and clone the repository onto an EC2 instance.

git clone  
cd 

Create and activate a virtual environment:

python3 -m venv venv
source venv/bin/activate

Install the necessary Python requirements (assuming the cloned repository contains a Requirements.txt document):

pip3 install -r requirements.txt

Run the server:

python3 -m uvicorn :app

Open the browser and enter the instance’s IP address.

Make sure to use the HTTP (not HTTPS) protocol. For example: http://16.16.202.153. A firewall may block your connection, but you should continue to open the web page. Add to /docs After the URL opens the fast API swagger.

exercise

If you want to run a FastApi example, you can create a simple repository that consists of only one main.py File and a Requirements.txt.

main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

Requirements.txt

fastapi
uvicorn

Upload file

If you try to upload the file to the server and receive a 413 status with an error message “Error: The requested entity is too large”this may be because Nginx has a limit on the maximum file size that can be uploaded. To resolve this issue, go to the NGINX configuration file and specify the maximum allowed file size by using the file client_max_body_size Directive (setting it to 0 means there is no limit on the input file size):

server {
  listen 80;
  server_name ;
  location / {
    proxy_pass 
    client_max_body_size 0;
  }
}

After changing the configuration file, don’t forget to restart NGINX.

in conclusion

In this article, we learned how to quickly create running EC2 instances using FastAPI server. Although we do not follow the best deployment and security practices, the main goal of this article is to provide beginners with minimal information to start their first server on AWS.

The next logical step in the AWS research roadmap is to create multiple EC2 instances and connect them to each other.

Unless otherwise stated, all images are by the author.

Contact me

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button