Ultimate Guide: FastAPI Docker Integration — Best Practices & Deployment

Jennie Lee
6 min readMar 25, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Introduction to 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. It is designed to be easy to use and to provide high productivity and performance. FastAPI has gained popularity due to its simplicity, scalability, and support for asynchronous programming. With its automatic validation and serialization, FastAPI makes it easy to develop robust web applications.

Docker, on the other hand, is an open-source platform that allows developers to automate the deployment and management of applications using containerization. Containers are lightweight, isolated environments that package all the necessary dependencies and configurations required for an application to run. Docker allows applications to run consistently across different environments, making it easier to build, ship, and deploy applications.

In this tutorial, we will explore the integration of FastAPI and Docker. We will learn how to containerize a FastAPI application using Docker, which allows us to isolate our application and its dependencies from the host system. We will also use docker-compose to orchestrate multiple containers and easily manage our application’s development environment.

Setting up the Project

First, let’s set up a new project directory and navigate to it. Open your terminal or command prompt and run the following commands:

mkdir fastapi-docker-tutorial
cd fastapi-docker-tutorial

Next, we need to configure a virtual environment inside the project directory. Virtual environments are isolated Python environments that allow us to install project-specific dependencies without affecting the system-wide Python installation. Run the following command to create a virtual environment:

python -m venv .venv

After creating the virtual environment, we need to activate it. Run the appropriate command for your operating system:

  • Windows:
.venv\Scripts\activate
  • macOS/Linux:
source .venv/bin/activate

Now that we have activated the virtual environment, let’s initialize our project using Poetry. Poetry is a Python dependency management and packaging tool that simplifies the management of project dependencies.

To initialize the project, run the following command:

poetry init

This command will guide you through a series of prompts to configure the project metadata. You can press enter to accept the default values for most prompts. At the end of the process, a pyproject.toml file will be generated, which includes the project metadata and dependencies.

Creating the FastAPI Application

Now that our project is set up, let’s create the FastAPI application. In the project directory, create a new directory called app:

mkdir app

Navigate into the app directory:

cd app

Inside the app directory, create a new file called app.py. This file will contain our FastAPI application code. Open the app.py file in your preferred text editor and add the following code:

from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})

In this code, we import the necessary modules from FastAPI and create a FastAPI application instance called app. We also import the Jinja2Templates class from fastapi.templating module to support HTML templates. We define a single route at the root URL ("/") that returns an HTML response using a template called index.html. We pass the request object to the template context to access request information inside the template.

Next, let’s create the templates directory inside the app directory and add an index.html file. Inside the templates directory, create a new file called index.html and add the following HTML code:

<!DOCTYPE html>
<html>
<head>
<title>FastAPI Docker Tutorial</title>
</head>
<body>
<h1>Welcome to the FastAPI Docker Tutorial!</h1>
</body>
</html>

This HTML code simply displays a heading that says “Welcome to the FastAPI Docker Tutorial!”.

Installing Dependencies

Now that we have created our FastAPI application, let’s install the project dependencies. Run the following command in your terminal or command prompt:

poetry install

This command will read the pyproject.toml file and install the specified dependencies into the virtual environment.

Containerizing the FastAPI Application

To containerize our FastAPI application, we need to create a Dockerfile. The Dockerfile is a text file that contains a set of instructions for building a Docker container image.

In your project directory, create a new file called Dockerfile and open it in your text editor. Add the following code to the Dockerfile:

FROM python:3.11.2

RUN pip install poetry

WORKDIR /app

COPY pyproject.toml poetry.lock ./
RUN poetry install --no-root

COPY . .

EXPOSE 8000

CMD ["poetry", "run", "uvicorn", "app.app:app", "--host", "0.0.0.0", "--port", "8000"]

In this Dockerfile, we start with the official Python 3.11.2 image as the base image. We then install Poetry inside the container using the pip package manager, which allows us to manage our project dependencies. We set the working directory to /app inside the container and copy the pyproject.toml and poetry.lock files. We install the project dependencies with Poetry using the --no-root flag to exclude the root package. Finally, we copy the rest of the project files, expose port 8000, and specify the command to run the FastAPI application using Poetry and uvicorn.

Orchestration with docker-compose

To easily manage our application’s development environment and orchestrate our containers, we will use docker-compose. Docker-compose allows us to define and run multiple containers as a single service.

In your project directory, create a new file called docker-compose.yml and open it in your text editor. Add the following code to the docker-compose.yml file:

version: "3.8"

services:
tutorial:
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
volumes:
- .:/app
- .venv:/app/.venv
command: poetry run uvicorn app.app:app --host 0.0.0.0 --port 8000

In this docker-compose.yml file, we define a service called tutorial that builds the container using the previously created Dockerfile. We expose port 8000 to the host system and mount the current working directory and the .venv directory as volumes. This allows us to make code changes and see the changes reflected in the running container without having to rebuild the container. We also specify the command to be executed when the container starts, which runs the FastAPI application using Poetry and uvicorn.

Starting the Container

Now that we have set up our FastAPI application and the Docker configuration, we can start the container.

In your terminal or command prompt, ensure that you are in the project directory, and run the following command:

docker-compose up --build

This command will build the container and start the tutorial service inside the container. You should see the output from the container indicating that the FastAPI application is running. Leave the container running for now.

To test the application, open a web browser and navigate to http://localhost:8000. You should see the text "Welcome to the FastAPI Docker Tutorial!" displayed in the browser. Congratulations, your FastAPI application is now running inside a Docker container!

To stop the container, go back to your terminal or command prompt and press Ctrl+C. Then, run the following command to stop and remove the containers:

docker-compose down

Conclusion

In this tutorial, we have learned how to integrate FastAPI and Docker to containerize and deploy a FastAPI application. We started by setting up our project directory, creating the FastAPI application code, and installing the project dependencies using Poetry. We then containerized the application by creating a Dockerfile and defining the necessary instructions. We also used docker-compose to orchestrate the containers and manage the development environment easily.

By leveraging the power of FastAPI and Docker, we can develop, test, and deploy high-performance web applications with ease. Containerization allows us to isolate our application and its dependencies, making it easy to ship and deploy applications consistently across different environments.

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--