pythondjangodockerdocker-composedockerfile

Docker-compose can't import Django (ModuleNotFoundError)


I'm very new to Docker, and I've been trying to get a very simple 'Hello World' program to run on docker. No matter what I do I always get:

ModuleNotFoundError: No module named 'Django'

What am I doing wrong?

Here's the terminal output.

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

Here's the 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/

And here is the docker-compose.yml file:

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

Edit

This is the content of my 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"

Solution

  • instead of

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

    you may use:

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

    this is a snippet from here