skip to Main Content

I am dockerizing my Django application with docker multi-stage build. Now am facing an issue with dependencies

Dockerfile

FROM python:3.8-slim-buster AS base
WORKDIR /app
RUN python -m venv venv
ENV PATH="/app/venv:$PATH"
COPY requirements.txt .
RUN pip install -r requirements.txt 
    && pip install gunicorn
COPY entrypoint.sh .
COPY . .

FROM python:3.8-slim-buster
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY --from=base /app /app/
ENV PATH="/app/venv:$PATH"
ENTRYPOINT sh entrypoint.sh

When running the container it raises import error.

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?

2

Answers


  1. I went to the same situation few month ago and it was a conflict between 2 packages, so django was not installed during the pip install.

    You can add on your docker build command the ‘–progress=plain’ option and see if everything is ok, during the docker build :

    • $ docker build –no-cache –progress=plain -t my_service_name .
      Baptiste.
    Login or Signup to reply.
  2. here is a working multistage docker build for django.

    ENV PYTHONBUFFERED 1
    WORKDIR /opt/webapp/
    
    ENV VIRTUAL_ENV=/opt/venv
    RUN python3 -m venv $VIRTUAL_ENV
    ENV PATH="$VIRTUAL_ENV/bin:$PATH"
    # copy requirements.txt
    COPY ./requirements.txt /opt/webapp/requirements.txt
    RUN pip3 install -r requirements.txt --no-cache-dir
    
    # runner stage
    FROM python:3.8-slim-buster AS runner
    
    ARG SECRET_KEY
    ARG DEBUG
    
    WORKDIR /opt/webapp
    RUN groupadd -r django 
      && useradd -d /opt/webapp -r -g django django 
      && chown django:django -R /opt/webapp
    USER django
    
    COPY --from=builder /opt/venv /opt/venv
    ENV PATH="/opt/venv/bin:$PATH"
    
    COPY --chown=django:django . /opt/webapp/
    
    # run the server
    CMD gunicorn conf.wsgi:application --bind 0.0.0.0:8000
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search