要在FastAPI中实现Docker容器化,可以按照以下步骤操作:
- 创建一个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"]
- 创建一个requirements.txt文件,列出FastAPI所需的所有依赖包。
fastapi
uvicorn
- 在FastAPI应用程序的根目录下创建一个main.py文件,其中包含FastAPI应用程序的代码。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
- 构建Docker镜像。
在包含Dockerfile文件的目录下执行以下命令来构建Docker镜像:
docker build -t fastapi-app .
- 运行Docker容器。
执行以下命令来运行Docker容器:
docker run -d --name fastapi-container -p 80:80 fastapi-app
现在,您的FastAPI应用程序已经容器化,并通过Docker容器运行。您可以通过访问 http://localhost 来访问应用程序。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1024014.html