Docker部署detectron2修改Python版本解决版本不兼容报错
问题原因
容器内运行环境与宿主机完全隔离,出现Python 3.6.9版本的原因有两点:
- 使用的基础镜像
nvidia/cuda:11.1.1-cudnn8-devel-ubuntu18.04基于Ubuntu 18.04,系统apt源默认预装的Python3版本就是3.6.9 - Dockerfile中显式下载了Python 3.6专属的pip安装脚本,进一步固定了Python 3.6的运行环境
修复方案
直接调整Dockerfile配置即可,核心修改点:
- 替换基础镜像为Ubuntu 20.04版本的CUDA 11.1镜像,该版本系统默认Python3为3.8,满足detectron2要求的
>=3.7版本约束,同时apt源自带的python3-opencv可正常适配,不会出现旧版本注释提到的兼容性问题 - 移除单独下载Python3.6版本get-pip.py的逻辑,直接通过apt安装对应版本的pip
- 保留原有非root用户配置、CUDA架构参数、依赖安装逻辑不变
修改后的完整Dockerfile如下:
FROM nvidia/cuda:11.1.1-cudnn8-devel-ubuntu20.04 ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -y \ python3-opencv ca-certificates python3-dev python3-pip git wget sudo ninja-build RUN ln -sv /usr/bin/python3 /usr/bin/python # 创建非root用户 ARG USER_ID=1000 RUN useradd -m --no-log-init --system --uid ${USER_ID} appuser -g sudo RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers USER appuser WORKDIR /home/appuser ENV PATH="/home/appuser/.local/bin:${PATH}" # 安装依赖 # 如需使用其他CUDA版本,可自行匹配对应PyTorch版本 RUN pip install --user tensorboard cmake # apt源安装的cmake版本过旧,使用pip版本 RUN pip install --user torch==1.10 torchvision==0.11.1 -f https://download.pytorch.org/whl/cu111/torch_stable.html RUN pip install --user 'git+https://github.com/facebookresearch/fvcore' # 安装detectron2 RUN git clone https://github.com/facebookresearch/detectron2 detectron2_repo # docker build阶段无法访问CUDA,强制开启CUDA编译 ENV FORCE_CUDA="1" # docker build阶段无法识别目标显卡架构,默认编译全通用架构会增加构建耗时 ARG TORCH_CUDA_ARCH_LIST="Kepler;Kepler+Tesla;Maxwell;Maxwell+Tegra;Pascal;Volta;Turing" ENV TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST}" RUN pip install --user -e detectron2_repo # 固定模型缓存目录 ENV FVCORE_CACHE="/tmp" WORKDIR /home/appuser/detectron2_repo # 运行示例(取消注释即可测试): # wget http://images.cocodataset.org/val2017/000000439715.jpg -O input.jpg # python3 demo/demo.py \ #--config-file configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \ #--input input.jpg --output outputs/ \ #--opts MODEL.WEIGHTS detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl
后续操作
修改完成后,执行以下命令禁用缓存重新构建镜像,再启动服务即可:
docker compose build --no-cache docker compose up -d
若必须保留Ubuntu 18.04基础镜像,可通过添加deadsnakes软件源的方式安装Python3.8及以上版本,但该方案会提升依赖冲突概率,优先选择更换基础镜像的方案。
内容的提问来源于stack exchange,提问作者amd
相关产品推荐
相关产品推荐

