要在FastAPI中實現Docker容器化,可以按照以下步驟操作:
# Use an official Python runtime as a parent image
FROM python:3.8-slim
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
fastapi
uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
在包含Dockerfile文件的目錄下執行以下命令來構建Docker鏡像:
docker build -t fastapi-app .
執行以下命令來運行Docker容器:
docker run -d --name fastapi-container -p 80:80 fastapi-app
現在,您的FastAPI應用程序已經容器化,并通過Docker容器運行。您可以通過訪問 http://localhost 來訪問應用程序。