Master Docker: Build and Containerize Python Web App (FastAPI) 🐍🐳 | Easy Tutorial
In this easy tutorial, we will learn how to build and containerize a Python web app using FastAPI and Docker. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Docker is a platform for developers and sysadmins to develop, package, and deploy applications as containers.
Prerequisites
Before we start, make sure you have Docker installed on your system. You can download and install Docker from the official website: https://www.docker.com/products/docker-desktop
Building the Python Web App with FastAPI
First, let’s create a simple Python web app using FastAPI. Create a new directory for your project and create a file named main.py
with the following content:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
Save the file, and now you have a simple FastAPI web app that responds with a JSON object when you visit the root URL.
Containerizing the Python Web App with Docker
Now, let’s containerize our Python web app using Docker. Create a new file named Dockerfile
in the same directory as your main.py
file with the following content:
# Use the official Python image from the Docker Hub
FROM python:3.8
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install the required Python packages
RUN pip install fastapi uvicorn
# Expose the port on which the FastAPI web app will run
EXPOSE 80
# Command to run the FastAPI web app using uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Save the file, and now you have a Dockerfile that defines how your Python web app will be containerized.
Building and Running the Docker Container
Open a terminal and navigate to the directory where your project is located. Build the Docker image by running the following command:
docker build -t my-python-web-app .
This command will build a Docker image named my-python-web-app
using the Dockerfile in the current directory. Once the image is built, you can run it as a container using the following command:
docker run -d -p 8000:80 my-python-web-app
This command will start a new Docker container based on the my-python-web-app
image and forward port 80 of the container to port 8000 on your local machine. You can now access your Python web app by visiting http://localhost:8000
in your web browser.
Conclusion
Congratulations! You have successfully built and containerized a Python web app using FastAPI and Docker. You can now easily share and deploy your web app as a container, making it portable and scalable across different environments.
Keep them coming 😅
Wow! Amazing!