3

I am new in Docker and learning it, and my question is that do I have to use venv in Docker or isn't it important? Because I couldn't configure venv in docker, it gives me an error like cannot import Django activate venv..., I read some answers but couldn't get answer, some people say need to use venv others not important.

My DOckerfile

FROM python:3.8

#set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN python3 -m venv venv

#Set work directory
WORKDIR /code/

#Install dependencies
COPY requirements.txt .
RUN . /venv/bin/activate && pip install -r requirements.txt

COPY . /code/

If I don't use venv Docker runs fine, but when it comes to install package it gives me warning like WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead:... Can someone explain clearly it?

Thanks in advance

mirodil
  • 422
  • 2
  • 8
  • 21
  • 1
    Using a venv in Docker is completely unnecessary IMO. I have never used one and have never had any issues, not using one is ever so slightly simpler too – Iain Shelvington Dec 29 '21 at 16:43
  • If you are annoyed by this message, you could add new user in your Dockerfile and install things in user's home directory specifying `--user` flag in your pip command , but as @IainShelvington said already this is completely unnecessary. Question is duplicate anyway: https://stackoverflow.com/questions/68673221/warning-running-pip-as-the-root-user – w8eight Dec 29 '21 at 17:18
  • 1
    Does this answer your question? [WARNING: Running pip as the 'root' user](https://stackoverflow.com/questions/68673221/warning-running-pip-as-the-root-user) – w8eight Dec 29 '21 at 17:19
  • I wanted full explanation why and why not to use venv in Docker – mirodil Dec 29 '21 at 17:28

1 Answers1

3

What's the difference between Docker and Python virtualenv?

A virtualenv only encapsulates Python dependencies. A Docker container encapsulates an entire OS.

In other words, a docker container is similar to a virtual environment except that it encapsulates its own OS instead of its own project environment. This means a virtual environment would be useless to have inside of a docker container since the environment is already encapsulated.