栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Python FastApi:快速建立docker容器/挂载共享文件夹/导入导出

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python FastApi:快速建立docker容器/挂载共享文件夹/导入导出

一、目的

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="0.0.0.0", port=8084)

2.构建docker镜像
docker build -t imamgeName .

 使用命令查找image是否存在

docker images
3.运行容器
docker run -d -p 8085:80 --name pytname  pyti2

运行命令查看容器状态

docker ps -a
4.浏览器访问fastapi

四、挂载共享windows文件夹 1.运行命令

a.windows路径直接绝对路径,docker内路径也需要绝对路径。

b.可以不需要参数 -it,不显示交互信息

docker run -v C:testFile:/app/img -d -p 8087:80 --name pyshare4 pyti2

PS:有时莫名其妙不能挂载。考虑增加参数--restart always --privileged=true

2.进入docker查看
docker exec -it pyshare4 /bin/bash

ps:有时遇到进入后卡住的问题

参考:docker run -it 和 docker exec -it_wdadas的博客-CSDN博客

五、遇到问题与总结

a.当需要安装python lib比较特别时,就需要很耗时查找,就不快速了。

b.可扩展性不高。

六、导入导出镜像

save--load

export --import

要一一对应,否则报错:

docker: Error response from daemon: No command specified.

参考:Docker 导入导出镜像_bear_依旧。的博客-CSDN博客

参考:Docker实践:python应用容器化 - 三只松鼠 - 博客园

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307522.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号