Deploy FASTAPI on AWS EC2
Launch an EC2 Instance
After register an AWS account, go to Console Home and click to EC2 Dashboard. Config an EC2 Instance as following:
Name
Machine Image: Ubuntu (Latest long term supported version)
Instance Type: t2.micro
- Create a
Key pairto login by ssh
Key pair name
Key pair type: RSA
Private key format: .pem
Once you've created a key, you will see a key downloaded.
- Network Settings
Allow ssh traffic form: anywhere
Allow http access from the internet
Allow https access from the internet
Launch instance! Go back to the EC2 dashboard and you will see your instance is running like:
Information like public IP can be viewed:
Connect to the instance
Login by SSH client (Mac or Linux)
chomd 400 [name].pem
Then just copy the ssh command.Remember you need to go to the directory where your pem file stored before paste the SSH command on your terminal. You will see this after login:
Server settings
sudo apt install -y python3-pip nginx
Create configuration file:
sudo vim /etc/nginx/sites-enabled/fastapi_nginx
server {
listen 80;
server_name 18.116.199.161;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
sudo service nginx restart
Then clone your FASTAPI project to your server.
Install all the dependencies and packages by:
pip3 install -r requirement.txt
Start the FASTAPI
python3 -m uvicorn --host 0.0.0.0 main:app
Increase EC2 storage
I found the 8 GiB is not enough for my project so I decided to upgrade the storage.
-
Click on EC2 instance and then go to the storage session
-
Then modify the volume:
-
So far we have increase the size of EC2, we need to cofig our server by ssh login
-
List block devices,
svda1is your original hard drivelsblk -
Increase our partition
sudo growpart /dev/xvda 1You can see the volume increse by
lsblk -
Extend our file system
sudo resize2fs /dev/xvda1You should see the volume got extend
Security Setting
If new port needed (default 80), you may consider to add a rule:
TCP [port] 0.0.0.0/0(all ports)
Test connection
netcat [ip address] [port]
curl http://[ip address]:[port]
A common problem is the Chorme may automatically set http->https, whcih may result in Invalid HTTP request received. One way to solve this is to deploy the frontend to the server as well.
Another problem may encounter is Mixed Content: This request has been blocked; the content must be servered over HTTPS. You can add
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
at the haed part of your public/index.html of your React front-end.