FastAPI中怎么实现Docker容器化

17次阅读
没有评论

共计 957 个字符,预计需要花费 3 分钟才能阅读完成。

要在 FastAPI 中实现 Docker 容器化,可以按照以下步骤操作:

  1. 创建一个 Dockerfile 文件来定义 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"]
  1. 创建一个 requirements.txt 文件,列出 FastAPI 所需的所有依赖包。
fastapi
uvicorn
  1. 在 FastAPI 应用程序的根目录下创建一个 main.py 文件,其中包含 FastAPI 应用程序的代码。
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}
  1. 构建 Docker 镜像。

在包含 Dockerfile 文件的目录下执行以下命令来构建 Docker 镜像:

docker build -t fastapi-app .
  1. 运行 Docker 容器。

执行以下命令来运行 Docker 容器:

docker run -d --name fastapi-container -p 80:80 fastapi-app

现在,您的 FastAPI 应用程序已经容器化,并通过 Docker 容器运行。您可以通过访问 http://localhost 来访问应用程序。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-13发表,共计957字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)