背景
docker使用了paddle库,并且需要将paddle打包到项目lib文件夹,因此需要完成的工作有3步:
- 打包paddle相关库到lib文件夹下。
- 构建docker镜像。
- 安装镜像并且运行容器使用GPU资源。
打包项目的python依赖到lib文件夹
paddle-gpu的安装:https://editor.youkuaiyun.com/md/?articleId=143920262
打包到项目的lib文件夹的方法,使用的poetry管理项目,因此在pyproject.toml中添加相关的paddle依赖:
paddlepaddle-gpu="~2.6.2"
paddleocr = "^2.9.1"
poetry支持本地化安装(在官方网站下载whl镜像,放在当前目录,然后使用本地化安装):
paddlepaddle-gpu= {path = "paddlepaddle_gpuxxxx.whl"}
- 安装相关软件:
poetry update -vv
- 导出依赖
poetry export --without-hashes -f requirements.txt --output requirements.txt
- 安装依赖库
# Linux 更新lib版本可先清空目录
python3 -m pip install -r requirements.txt --upgrade --no-warn-conflicts --target ./lib
- 使用依赖库
export PYTHONPATH="./lib"
使用完毕依赖库后,可以使用pip list
查看是否成功引用刚刚安装的依赖库。
构建docker镜像
- 编写dockerfile文件(以dockerfile命名):
如果代码中使用了OpenCV,需要涉及部分图像库的依赖,在Ubuntu系统下,需要安装依赖
FROM python:3.12
WORKDIR /app
COPY . /app
RUN apt-get update
RUN apt-get install ffmpeg libsm6 libxext6 -y # 使用的相关图像依赖库
ENV xxx # 镜像使用的environment环境变量
EXPOSE 12345 # 使用的端口号
CMD [ "python", "./test.pyc"] #如果是web服务,则涉及到启动方式
- 完成docker镜像构建
把dockerfile文件放在需要打包的目录下,然后进行打包
docker build . -t {image_name}
#如: docker build . -t test_images:v1
安装镜像并且运行容器使用GPU资源
在启动容器的时候,需要指定–gpus all参数,这个时候才能调用宿主机的GPU资源,否则无法使用。
docker run --rm -it --gpus all -v -itd -p 12345:{your port} --name {container_name} {image_name}
# docker run --rm -it --gpus all -v -itd -p 12345:12345 --name test_GPU test_images:v1
完成后使用docker ps
指令查看安装好的容器。
将容器外部文件拷入容器内
一般经常变动的容器会挂载目录到宿主机,可能存在某些未挂载目录需要改动文件的情况,这个时候可以使用指令:
docker cp {source} {target}