DEV Community

Cover image for FastAPI & Docker: How to Build Scalable Microservices in 2024
Muhammad Haris
Muhammad Haris

Posted on

FastAPI & Docker: How to Build Scalable Microservices in 2024

Building a Microservice with FastAPI and Docker: A Step-by-Step Guide

Microservices architecture is a powerful approach for scalable and maintainable applications. In this tutorial, you’ll learn how to build a FastAPI microservice and deploy it using Docker containers for seamless development and production workflows.

Why Use FastAPI and Docker for Microservices?

FastAPI is a high-performance Python framework ideal for building RESTful APIs, while Docker simplifies containerized deployment. Together, they enable developers to create scalable microservices with minimal overhead.

Setting Up a FastAPI Microservice

Prerequisites

  • Python 3.7+
  • pip (Python package manager)

Step 1: Create a FastAPI Project

Start by setting up a new project directory and activating a virtual environment:

mkdir fastapi_microservice  
cd fastapi_microservice  
python3 -m venv venv  
source venv/bin/activate  # On Windows: `venv\Scripts\activate`  
Enter fullscreen mode Exit fullscreen mode

Install FastAPI and Uvicorn (an ASGI server):

pip install fastapi uvicorn  
Enter fullscreen mode Exit fullscreen mode

Step 2: Build a Basic API Endpoint

Create main.py with a simple endpoint:

from fastapi import FastAPI  

app = FastAPI()  

@app.get("/")  
def read_root():  
    return {"message": "Welcome to your FastAPI microservice"}  
Enter fullscreen mode Exit fullscreen mode

Run the server:

uvicorn main:app --reload  
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:8000 to test your API.

Containerizing the Microservice with Docker

Step 1: Install Docker

Ensure Docker is installed on your system.

Step 2: Create a Dockerfile

Define your container setup in a Dockerfile:

FROM python:3.9-slim  
WORKDIR /app  
COPY requirements.txt .  
RUN pip install --no-cache-dir -r requirements.txt  
COPY . .  
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]  
Enter fullscreen mode Exit fullscreen mode

Step 3: Build and Run the Docker Container

Build the image:

docker build -t fastapi-microservice .  
Enter fullscreen mode Exit fullscreen mode

Run the container:

docker run -d -p 8000:8000 fastapi-microservice  
Enter fullscreen mode Exit fullscreen mode

Your FastAPI microservice is now running inside a Docker container, ready for deployment.

Best Practices for FastAPI and Docker Microservices

  • Modularize your code for better maintainability.
  • Use environment variables for configuration.
  • Optimize Docker layers to reduce image size.
  • Monitor performance with logging and metrics.

By following this guide, you’ve built a scalable microservice using FastAPI and Docker, ensuring efficient development and deployment. Happy coding!

Top comments (0)