Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

Using FastAPI inside a Docker container

5 min read

Python has long been a favourite among developers for its simplicity and readability. Over the years, it has found its place in various domains of software development, including web development. While Python web frameworks like Django and Flask have been popular choices for building web applications, a relatively new player on the scene is gaining significant traction – FastAPI.

FastAPI, a modern Python web framework, has gained immense popularity for building APIs and web applications due to its speed, simplicity, and automatic documentation generation. When it comes to deploying FastAPI applications, Docker containers provide an efficient and consistent way to package your application, its dependencies, and its runtime environment. In this blog post, we’ll explore how to use FastAPI inside Docker containers, enabling you to containerize and deploy your FastAPI applications with ease

Before we jump into the containerisation journey with the FastAPI app, let us explore what makes FastAPI the future of Python web development.

Modern, Async-first Design

FastAPI is designed with modern web development practices in mind. It leverages asynchronous programming, making it highly efficient for handling concurrent requests. With the increasing demand for real-time and responsive web applications, FastAPI’s async-first design is a game-changer. It allows developers to write code that can handle thousands of requests concurrently, which is crucial for building modern, high-performance web services.

from fastapi import FastAPI

app = FastAPI()

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

Automatic Documentation

One of FastAPI’s standout features is its automatic API documentation generation. Using standard Python type hints, FastAPI can generate detailed API documentation that includes request and response models, route descriptions, and even interactive testing interfaces. This feature significantly speeds up the development process and ensures that your API documentation remains up to date as your code evolves.

Type Hinting and Validation

FastAPI leverages Python’s type hinting system to perform data validation and serialization automatically. This not only helps catch errors early in the development process but also improves the overall reliability of your application. FastAPI can validate request data against defined models, and if the data doesn’t match the expected types, it returns appropriate error responses, all without requiring explicit validation code.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    # item is automatically validated and of the correct type
    return item

High Performance

FastAPI’s performance is impressive. It’s built on top of Starlette, an asynchronous web framework, and Pydantic, a data validation and parsing library. These underlying technologies enable FastAPI to achieve low latency and high throughput, making it suitable for both small and large-scale applications. It’s common to see FastAPI outperform many other web frameworks in benchmark tests.

Ecosystem and Extensions

FastAPI benefits from the Python ecosystem. You can easily integrate it with various databases, ORMs (Object-Relational Mappers), and other third-party libraries. Additionally, the community has developed numerous extensions and middleware to enhance FastAPI’s capabilities. Whether you need authentication, database connectors, or custom serialization, you’ll likely find a package that suits your needs.

Production-Ready

FastAPI is not just for prototyping or small projects. It’s production-ready and used by many companies in real-world applications. With its automatic documentation, built-in validation, and performance optimizations, FastAPI can streamline the development and maintenance of large, complex web services.

Strong Community and Support

FastAPI has gained a strong and active community of developers who contribute to its growth and provide support through forums, GitHub issues, and tutorials. This community-driven approach ensures that the framework continues to evolve and stay relevant in the ever-changing landscape of web development.

Why Use Docker for FastAPI?

Docker offers several compelling reasons for deploying FastAPI applications:

  • Isolation: Docker containers encapsulate your application and its dependencies, ensuring consistent behavior across different environments, from development to production.
  • Portability: Docker containers can run on various platforms, including local development machines, cloud servers, and container orchestration platforms like Kubernetes.
  • Version Control: Docker allows you to version your application as a container image, making it easier to manage and roll back to previous versions.
  • Scaling: Docker containers are well-suited for horizontal scaling, enabling you to handle increased traffic by running multiple instances of your FastAPI application.

Building a Docker Image for FastAPI

To containerize a FastAPI application, you’ll need to create a Docker image. Here are the steps to do that:

1. Create a Dockerfile

In your project directory, create a file named Dockerfile (without any file extension). This file defines the steps to build your Docker image. Here’s a simple example:

Dockerfile

# Use the official Python image as the base image
FROM python:3.9-slim

# Set the working directory inside the container
WORKDIR /app

# Copy the requirements.txt file into the container
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of your application code into the container
COPY . .

# Expose port 80 (or the port your FastAPI app is running on)
EXPOSE 80

# Command to run your FastAPI application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

2. Create a requirements.txt File

Ensure you have a requirements.txt file that lists all the Python dependencies required for your FastAPI application. You can generate this file using pip freeze:

pip freeze > requirements.txt

3. Build the Docker Image

Navigate to your project directory in the terminal and run the following command to build your Docker image:

docker build -t fastapi-app .

The -t flag allows you to tag your image with a name (fastapi-app in this case).

4. Run the Docker Container

Once the image is built, you can run a Docker container from it:

docker run -p 80:80 fastapi-app

The -p flag maps port 80 inside the container to port 80 on your host machine.

5. Access Your FastAPI Application

Your FastAPI application is now running inside a Docker container. You can access it in your web browser or using tools like curl at http://localhost:80.

Docker Compose for Multi-Container Applications

For more complex applications that require multiple services (e.g., a database alongside your FastAPI app), Docker Compose is a powerful tool. You can define your entire application stack, including FastAPI, its dependencies, and any supporting services, in a docker-compose.yml file. Then, you can start your entire application stack with a single command:

Here’s an example docker-compose.yml file for running a FastAPI application along with a PostgreSQL database as a backend service. This assumes you have a FastAPI application with a PostgreSQL database as a dependency. You can modify it according to your specific requirements.

version: '3'
services:
  # FastAPI Application
  fastapi-app:
    image: fastapi-app-image  # Replace with the actual name of your FastAPI Docker image
    ports:
      - "80:80"  # Map container port 80 to host port 80
    depends_on:
      - postgres-db  # Depend on the PostgreSQL service

  # PostgreSQL Database
  postgres-db:
    image: postgres:13  # Use a PostgreSQL Docker image
    environment:
      POSTGRES_DB: mydatabase  # Replace with your database name
      POSTGRES_USER: myuser  # Replace with your database user
      POSTGRES_PASSWORD: mypassword  # Replace with your database password
    ports:
      - "5432:5432"  # Map container port 5432 to host port 5432

In this docker-compose.yml file:

  • We define two services: fastapi-app and postgres-db.
  • fastapi-app is your FastAPI application. You should replace fastapi-app-image with the actual name of the Docker image you built for your FastAPI application. We map port 80 inside the container to port 80 on the host.
  • postgres-db is a PostgreSQL database service. We use the official PostgreSQL Docker image. You can configure the database name, user, and password as environment variables.
  • The depends_on directive ensures that the FastAPI application service waits for the PostgreSQL service to be up and running before starting.

With this docker-compose.yml file, you can start your FastAPI application and PostgreSQL database together with a single command:

docker compose up

This setup is useful for running multi-container applications like FastAPI with a database, and it simplifies the deployment and management of your application stack.

Conclusion

FastAPI has quickly become a dominant player in Python web development due to its modern design, automatic documentation, type hinting, and performance. Its simplicity and efficiency make it a top choice for building APIs, microservices, and web applications. As the demand for high-performance, real-time applications continues to rise, FastAPI is well-positioned to lead the future of Python web development.

If you’re a Python developer looking to build fast, reliable, and well-documented web services, FastAPI is a tool you should consider adding to your toolkit. Its future in the world of web development looks promising, and it’s likely to continue gaining popularity and support within the developer community.

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).
Join our Discord Server
Index