无法在GitLab CI上的docker镜像中导入django

我试着在gitlab ci中运行我的djangotestingpython manage.py test 。 因此,我正在使用一个泊坞窗图像。 泊坞窗图像生成的罚款,但是当它运行在gitlab上的testing我得到ImportError: No module named 'django'

 Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 

看我的.gitlab-ci.yml

 image: registry.gitlab.com/app/core:latest services: - postgres:latest stages: - test variables: SECRET_KEY: test-secret POSTGRES_DB: ... POSTGRES_USER: ... POSTGRES_PASSWORD: ... python_tests: stage: test before_script: - export DATABASE_NAME=... - export DATABASE_USER=... - export DATABASE_PASSWORD=... - export DATABASE_HOST=postgres - source /app/venv/bin/activate script: - python manage.py test 

Dockerfile

 FROM ubuntu:16.04 RUN apt-get update -y -qq RUN apt-get install -y -qq build-essential libffi-dev libpq-dev libfontconfig1 RUN apt-get install -y -qq python3 python3-dev python3-pip RUN apt-get install -y -qq libpq-dev RUN apt-get install -y -qq nodejs npm WORKDIR /app # pip COPY requirements.txt /app RUN pip3 install --upgrade pip RUN pip3 install virtualenv RUN virtualenv --no-site-packages venv RUN . venv/bin/activate RUN pip3 install -r /app/requirements.txt # npm RUN ln -s `which nodejs` /usr/bin/node COPY web/vueapp/package.json /app RUN npm install 

那么你的方法有一个问题。 在Dockerfile中考虑下面的RUN语句

 RUN . venv/bin/activate RUN pip3 install -r /app/requirements.txt 

上述两个语句就像是开放的两个terminal,一个执行. venv/bin/activate . venv/bin/activate并在一个pip3 install -r /app/requirements.txt

所以你的环境被激活,你让它closures,然后下一个pip3语句安装在全局包上。 所以把你的代码改成下面

 RUN . venv/bin/activate && pip3 install -r /app/requirements.txt 

当你的脚本运行的时候,你是激活环境,然后在没有包的空白的虚拟环境中运行python manager.py。 所以上面的改变应该为你解决这个问题