Here is a very simple example of how we can set up a dev environment for a FastAPI app with Docker.
Below is a simplified api endpoint with FastAPI:
# main.py
from fastapi import FastAPI, HTTPException, Response
app = FastAPI()
@app.get("/")
def read_root() -> Response:
return Response("Server is running...")
🐳 Dockerfile:
FROM python:3.11
# set working directory in container
WORKDIR /app
# install dependencies
COPY ./requirements.txt /app
RUN pip install --no-cache-dir --upgrade -r requirements.txt
# copy files to the folder
COPY . /app
# start server
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
We can build and run the Docker image with docker build -t my-api .
and docker run -d -p 8080:80 my-api
However, Docker compose will make things easier as we don't have to keep rebuilding and rerunning the server when changes are made to the code.
🛳️ docker-compose.yml:
services:
app:
build: . # folder we use to build container
container_name: fastapi-server
command: uvicorn main:app --host 0.0.0.0 --port 80 --reload # replaces CMD in Dockerfile
ports:
- 8080:80 # local port:container port
volumes:
- .:/app # sync current folder to app folder in container, overrides "COPY . /app" in Dockerfile
Build and run the container with docker-compose up --build