01: Hello Dockerized FastAPI

Building APIs has never been easier, thanks to modern web frameworks such as FastAPI. What's even better is deploying these APIs with tools like Docker to ensure consistency across various environments. This guide will walk you through setting up a simple FastAPI application and then containerizing it using Docker.

Let's start with the basics: a simple FastAPI application using a main.py file

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"msg":"ML API with FastAPI🚀"}

In the code above, we are creating a FastAPI application and defining a single route (/) that responds with a welcome message when accessed.

Containerizing with Docker

To run our application in a container, we first need to define the environment it requires. This is done using a Dockerfile. But before we dive into the docker-compose.yml file, that you've provided, let's discuss what's in it:

version: '3.9'

services:
  web:
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    environment:
      - ENV_VAR_NAME=VALUE
    volumes:
      - ./:/app
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload
  

In this Docker Compose configuration, we have 1 service: web: Our FastAPI application.

  • The web service builds the container image using the current directory (./) and a Dockerfile named Dockerfile.
  • We map the host's port 8000 to the container's port 8000, allowing us to access our FastAPI application.
  • We are using a volume to sync our local code with the /app directory in the container. This is especially helpful during development as it allows for hot-reloading.
  • We use the command to run our FastAPI application using Uvicorn.

Now, you might be wondering about the Dockerfile. Here's a simple Dockerfile to run our FastAPI application:

FROM python:3.9

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000

Since the Dockerfile mentions a requirements.txt file. We will need to create one.

fastapi==0.101.1
uvicorn==0.23.2

To run the entire setup simply use the command:

docker-compose up

This command will start all three services. You can access the FastAPI application at http://localhost:8000/.

FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial