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) $
Install FastAPI and Uvicorn.
(env) $ pip install fastapi uvicorn
In main.py file, Write
Hello, World!
program.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def index():
return {"details": "Hello, World!"}
run the server
(env) $ uvicorn main:app --reload --port=8000 --host=0.0.0.0
Open 127.0.0.1:8000
and see if it works.
Write dependencies into
requirements.txt
(env) $ pip freeze > requirements.txt
Create
Dockerfile
,.dockerignore
anddocker-compose.yaml
files
FROM python:3.8.10-slim
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
env/
__pycache__/
*.env
*.env.*
env.*
version: '3'
services:
web:
build: .
command: sh -c "uvicorn main:app --reload --port=8000 --host=0.0.0.0"
ports:
- 8000:8000
Run the docker container
(env) $ docker compose up --build
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)