DEV Community

Rajesh Joshi
Rajesh Joshi

Posted on • Edited on

Dockerize FastAPI project like a pro - Step-by-step Tutorial 🚀

Introduction 🔥

Are you a developer looking to containerize your FastAPI project using Docker?

In this step-by-step tutorial, we'll show you how to Dockerize your FastAPI app like a pro. From setting up your development environment to deploying your app to Docker Hub, we'll cover everything you need to know to get started with Docker and FastAPI.


Watch the video 🎥

For a better understanding, watch the tutorial video on Stackless Tech YouTube Channel.


Let's go 🚀

Start with creating and activating python virtual environment.

$ python3 -m venv env
$ source env/bin/activate
(env) $ 
Enter fullscreen mode Exit fullscreen mode

Install FastAPI and Uvicorn.

(env) $ pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

In main.py file, Write Hello, World! program.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def index():
    return {"details": "Hello, World!"}

Enter fullscreen mode Exit fullscreen mode

run the server

(env) $ uvicorn main:app --reload --port=8000 --host=0.0.0.0
Enter fullscreen mode Exit fullscreen mode

Open 127.0.0.1:8000 and see if it works.

Write dependencies into requirements.txt

(env) $ pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

Create Dockerfile, .dockerignore and docker-compose.yaml files

FROM python:3.8.10-slim

WORKDIR /app

COPY . /app

RUN pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode
env/
__pycache__/

*.env
*.env.*
env.*
Enter fullscreen mode Exit fullscreen mode
version: '3'

services:
  web:
    build: .
    command: sh -c "uvicorn main:app --reload --port=8000 --host=0.0.0.0"
    ports:
      - 8000:8000
Enter fullscreen mode Exit fullscreen mode

Run the docker container

(env) $ docker compose up --build
Enter fullscreen mode Exit fullscreen mode

Go to 127.0.0.1:8000, And it's now running from the Docker Container.


I hope you guys liked this quick tutorial

Cheers

Top comments (0)