Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable live-reload in a dockerised FastAPI application using Docker Compose

I have FastAPI app running in docker docker container. It works well except only one thing, the app doesn't reload if any changes are made in the source code. The changes are applied only if the container is restarted.

Here is the source code of my application so how do I ensure my containerised application automatically reloads each time I make some changes to the source code?

main.py

from typing import Optional
    
import uvicorn
from fastapi import FastAPI
    
app = FastAPI()
    
@app.get("/")
def read_root():
    return {"Hello": "World"}

    
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}
    
    
if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

docker-compose.yml

version: "3"
    
services:
  web:
    build: .
    restart: always
    command: bash -c "uvicorn main:app --host 0.0.0.0 --port 8000 --reload"
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
    
  db:
    image: postgres
    ports:
      - "50009:5432"
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=test_db
like image 642
dmitriy_one Avatar asked Sep 05 '25 03:09

dmitriy_one


1 Answers

this works for me

version: "3.9"

services:
  people:
    container_name: people
    build: .
    working_dir: /code/app
    command: uvicorn main:app --host 0.0.0.0 --reload
    environment:
      DEBUG: 1
    volumes:
      - ./app:/code/app
    ports:
      - 8008:8000
    restart: on-failure

this is my directory structure

.
├── Dockerfile
├── Makefile
├── app
│   └── main.py
├── docker-compose.yml
└── requirements.txt

make sure working_dir and volumes section's - ./app:/code/app match

example run:

docker-compose up --build

...
Attaching to people
people    | INFO:     Will watch for changes in these directories: ['/code/app']
like image 54
Kushagra Verma Avatar answered Sep 07 '25 20:09

Kushagra Verma