GitLab流水线测试作业提示pip未找到,如何实现依赖安装?
问题原因
你的test作业默认使用的是docker:24.0镜像,这个镜像仅包含Docker工具链,没有Python环境,自然找不到pip命令。同时build_image阶段只是构建了Python镜像,但没有让test作业复用该镜像,也未给test作业配置正确的Python运行环境。
解决方案
方案1:直接为test作业配置Python环境
修改.gitlab-ci.yml,给test作业指定Python镜像,覆盖默认的Docker镜像:
stages: - build - test default: image: docker:24.0 build_image: stage: build script: - docker build . test: stage: test image: python:3.12-slim # 指定Python镜像,与Dockerfile基础镜像一致 before_script: - apt-get update && apt-get install -y gcc # 可选:若你的包需要编译依赖则添加 script: - pip install --upgrade pip - pip install .[dev] - pytest
配置后test作业会在Python环境中运行,可直接调用pip。
方案2:复用build阶段构建的镜像
如果想让test作业使用已预装基础依赖的镜像,可将构建好的镜像推送到GitLab容器仓库,再让test作业拉取使用:
stages: - build - test default: image: docker:24.0 services: - docker:dind # 启用Docker-in-Docker,用于镜像构建与推送 build_image: stage: build variables: IMAGE_NAME: $CI_REGISTRY_IMAGE/my-python-app:$CI_COMMIT_SHORT_SHA script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $IMAGE_NAME . - docker push $IMAGE_NAME artifacts: reports: dotenv: image.env # 将镜像名称存入环境变量文件,传递给test作业 test: stage: test image: $IMAGE_NAME # 使用build阶段推送的镜像 script: - pip install .[dev] # 镜像已包含基础依赖,仅需安装dev依赖 - pytest
注意:需确保你的GitLab项目已启用容器Registry(路径:项目设置→Packages and Registries→Container Registry)。
内容的提问来源于stack exchange,提问作者Rishik Mani
相关产品推荐
相关产品推荐

