如何使用 Docker Compose 在 Docker 化的 FastAPI 应用程序中启用实时重新加载

dmi*_*one 21 docker-compose fastapi

我有 FastAPI 应用程序在 docker docker 容器中运行。它运行良好,除了一件事之外,如果源代码中进行任何更改,应用程序不会重新加载。仅当容器重新启动时,更改才会应用。

这是我的应用程序的源代码,那么如何确保每次对源代码进行一些更改时我的容器化应用程序都会自动重新加载?

主要.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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

小智 17

这对我有用

\n
version: "3.9"\n\nservices:\n  people:\n    container_name: people\n    build: .\n    working_dir: /code/app\n    command: uvicorn main:app --host 0.0.0.0 --reload\n    environment:\n      DEBUG: 1\n    volumes:\n      - ./app:/code/app\n    ports:\n      - 8008:8000\n    restart: on-failure\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的目录结构

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Dockerfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Makefile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 app\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 docker-compose.yml\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 requirements.txt\n
Run Code Online (Sandbox Code Playgroud)\n

确保working_dirvolumes部分的- ./app:/code/app匹配

\n

示例运行:

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Dockerfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Makefile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 app\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 docker-compose.yml\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 requirements.txt\n
Run Code Online (Sandbox Code Playgroud)\n


Luc*_*cas 9

您正在使用 启动容器docker compose up吗?这对我来说很有效,可以在 进行热重载http://127.0.0.1

version: "3.9"

services:
  bff:
    container_name: bff
    build: .
    working_dir: /code/app
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload
    environment:
      DEBUG: 1
    volumes:
      - .:/code
    ports:
      - "80:8000"
    restart: on-failure
Run Code Online (Sandbox Code Playgroud)

另外,我的应用程序中没有您的最后两行if __name__ ==等。不确定这是否会改变什么。