【问题标题】:Docker-compose can't import Django (ModuleNotFoundError)Docker-compose 无法导入 Django (ModuleNotFoundError)
【发布时间】:2020-03-29 16:31:12
【问题描述】:

我是 Docker 的新手,我一直在尝试让一个非常简单的“Hello World”程序在 docker 上运行。无论我做什么,我总能得到:

ModuleNotFoundError: 没有名为“Django”的模块

我做错了什么?

这是终端输出。

C:\path\to\app\root>docker-compose up
Creating network "hello-world_default" with the default driver
Creating hello-world_web_1 ... done                                                                                     Attaching to hello-world_web_1
web_1  | Traceback (most recent call last):
web_1  |   File "/code/manage.py", line 10, in main
web_1  |     from django.core.management import execute_from_command_line
web_1  | ModuleNotFoundError: No module named 'django'
web_1  |
web_1  | The above exception was the direct cause of the following exception:
web_1  |
web_1  | Traceback (most recent call last):
web_1  |   File "/code/manage.py", line 21, in <module>
web_1  |     main()
web_1  |   File "/code/manage.py", line 16, in main
web_1  |     ) from exc
web_1  | ImportError: 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?
hello-world_web_1 exited with code 1

这是 dockerfile

# Pull base image
FROM python:3.7

# Set environmental variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set work directory
WORKDIR /code

# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system

# Copy project 
COPY . /code/

这里是 docker-compose.yml 文件:

version: '3.7'
services:
  web:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000

编辑

这是我pipfile的内容:

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
pytz = "==2019.3"
sqlparse = "==0.3.1"
Django = "==2.2.7"

[requires]
python_version = "3.7"

【问题讨论】:

标签: python django docker docker-compose dockerfile


【解决方案1】:

您好,我刚刚解决了问题。 运行后

docker build .

运行docker-compose build 而不是docker-compose up

然后最后运行docker-compose up

【讨论】:

  • 谢谢。我读了同一本书,也遇到了同样的问题。
  • @DmytroManzhula 没问题。希望作者更新内容。
【解决方案2】:

而不是

COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system

你可以使用:

RUN pip install pipenv
COPY pipfile* /tmp
RUN cd /tmp && pipenv lock --requirements > requirements.txt
RUN pip install -r /tmp/requirements.txt

这是来自here的sn-p

【讨论】:

  • 谢谢。但不幸的是,这并没有解决问题。我仍然遇到同样的错误。
  • 还是不行。我什至尝试将pip install 命令与使用&amp;&amp; 的前一个命令结合起来,希望它可以通过在虚拟环境中实际安装包来解决问题。但是当我运行 docker-compose 时,我仍然得到相同的 Django not found 错误。
  • @SoroushParsa 只使用 requrements.txt 吗?
  • 你也可以发布你的 Pipfile 吗?
  • Pipfile Pipfile.lock 是您的 Pipfile.lock 的名称吗?
猜你喜欢
  • 2020-12-14
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
相关资源
最近更新 更多