a.快速把原有fastapi代码部署到docker,让docker在server运行。
b.不涉及docker深入设置。
c.使用python第三方lib少或简单。
二、步骤ps:请提前安装docker
1.新建Dockerfile,放入到项目根目录a.Dockerfile没有后缀.
b.准备好requirements.txt 文件
c.有些lib是比较特别和在pycharm导入的不一样需要手动修改,如opencv。
d.CaseTemplateMatch.py是fastapi实现功能文件
Dockerfile:
# 使用python环境运行fastapi py文件 FROM python:3.9 # Set the working directory to /app #ENV PATH /usr/local/bin:$PATH WORKDIR /app # Copy the current directory contents into the container at /app ADD . /app # Install any needed packages specified in requirements.txt RUN pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple RUN pip3 install opencv-python-headless -i https://pypi.tuna.tsinghua.edu.cn/simple # 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 ["python", "/app/CaseTemplateMatch.py"]
CaseTemplateMatch.py(部分)
import cv2
import numpy as np
from fastapi import FastAPI, File, UploadFile, Form
import uvicorn as uvicorn
import os
from starlette.responses import FileResponse
from pathlib import Path
import time
app = FastAPI()
@app.get("/copyFile/{fileName}")
async def copyFile(fileName: str):
"""
用于下载运行需要的工具,user用不到。文件预先放在server
:param fileName:
:return:
"""
downloadFile = './tool/' + fileName
my_file = Path(downloadFile)
if my_file.is_file():
printtimelog("dowload file"+fileName)
return FileResponse(downloadFile, filename=fileName)
if __name__ == '__main__':
uvicorn.run(app=app, host="127.0.0.1", port=8084)
2.构建docker镜像
docker build imamgeName .
使用命令查找image是否存在
docker images3.运行容器
docker run -d -p 8085:80 --name pytname pyti2
运行命令查看容器状态
docker ps -a4.浏览器访问fastapi
四、遇到问题与总结
a.当需要安装python lib比较特别时,就需要很耗时查找,就不快速了。
b.使用docker命令 ”-v“ 挂载文件,现在也没找到很好办法解决。(希望有大佬指出)
c.可扩展性不高。



