Step-by-Step Guidelines to Run Fast API in Containers
Step 1: Create a new folder for your project and navigate into it.
mkdir fastapi-container
cd fastapi-container
Step 2: Create a new Python virtual environment and activate it.
python -m venv env
.env/Scripts/activate
Step 3: Install FastAPI and Uvicorn in a virtual environment. Uvicorn is an application server used to serve Python web applications
pip install fastapi uvicorn
Step 4: Create your FastAPI files or add all the necessary files to your folder.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def hello():
return {"Hello": "World"}
Step 5: Create a new file called Dockerfile and add the following code. This will allow you to make docker image and container which will copy all the content from your directory into image.
Note: Make sure filename is Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
COPY . .
Step 6: Build the docker image using following syntax.
docker build -t fastapi-docker .
-t is a tag flag which allow you to name your docker image, in above case fastapi-docker.explanation,
Step 7: Run your image which will create container and run uvicorn at port 9000 (using –p flag) as given in below syntax.
docker run -p 9000:80 fastapi-docker
Step 8: Goto any browser and search this URL localhost:9000. This will show result from your endpoints.
FastAPI in Containers – Docker
FastAPI is also an open-source Starlette-ASGI (Asynchronous Server Gateway Interface) micro-web framework written in Python used to create RESTful APIs. Docker is a set of platform-as-a-service (PaaS) products that use OS-level virtualization to deliver software in packages called containers.
Your project has various dependencies and requires different configurations for each task, such as database management, cloud integration, CI/CD, etc. Setting up these configurations can be a hectic task, and they also need to be portable. To overcome this challenge, containers can be used. By building a Docker image and containers, you can develop an isolated environment for your project code with all the necessary dependencies. This article will guide you through the process of creating these containers.