Hi Everyone! π
This blog will see how we can deploy a FastAPI application on AWS EC2 instance using Docker and NGINX.
Step 1: Create an API using FastAPI
For this article, I have created a Github Repository. You can use this repository or create your API.
To use my GitHub Repository, Follow the steps mentioned in README.md
Step 2: Spin up your EC2 Instance
In this tutorial, I won't be going through how to spin up your EC2 instance. There are hundreds of tutorials over the internet on starting an EC2 instance.
Step 3: Install Docker and NGINX on your Server
To install Docker on your EC2 instance. Use the following commands:
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
To check if Docker is properly installed or not, Use the following command: sudo docker run hello-world
. This will pull hello-world
image from Docker Registry.
To install NGINX on your EC2 instance. Use the following command:
sudo apt install nginx
Step 4: Get all Application Files
Now that we have Docker and NGINX installed. It's time to get all our application files on EC2. If you are using my repository. Use the following command to clone the repo.
git clone https://github.com/theinfosecguy/fastapi
Step 5: Setup NGINX
After installing NGINX and getting all our files, let's configure NGINX on our EC2 instance.
- Use the following command to create NGINX Config File
sudo vi /etc/nginx/sites-enabled/fastapi-demo
This will create a fastapi-demo
file in the /etc/nginx/sites-enabled/
directory.
Paste the following server
block in opened vi
editor screen.
server {
listen 80;
server_name <PUBLIC_IP>;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
Replace <PUBLIC_IP>
with the Public IP of your EC2 instance.
Save the file by pressing the Esc key and then typing :x
and pressing Enter (Feel free to use any other text editor of your choice).
After saving the file, restart the NGINX server using the following command:
sudo service nginx restart
Step 6: Start the Docker Container
We will now start the Docker Container in Detached Mode so that Docker does not block our terminal. Use the following command to create the Docker container.
sudo docker-compose up -d
Here -d
represents Detached Mode. This will start the Docker Container inside which our application is running.
That's all, guys, Try to visit the server's public IP, and you'll see something like this.
You can play around with the API using Postman.
I hope you guys liked the article π. Drop a comment if you have any queries or have any questions β.
Top comments (1)
Hi Keshav, thanks for writing this post. Would like to know why would one need NGINX here ? Can't we spin up Fast API container & then access it using EC2 Public IP ??