107

How do you add a path to PYTHONPATH in a Dockerfile? So that when the container is run it has the correct PYTHONPATH? I'm completely new to Docker.

I've added ENV PYTHONPATH "${PYTHONPATH}:/control" to the Dockerfile as I want to add the directory /control to PYTHONPATH.

When I access the container's bash with docker exec -it trusting_spence bash and open python and run the commands below the directory control is not on the list.

import sys print(sys.path)

FROM python:2
RUN pip install requests pymongo

RUN mkdir control

COPY control_file/ /control

ENV PYTHONPATH "${PYTHONPATH}:/control"

CMD ["python","control/control_file/job.py"] 
0

3 Answers 3

159

Just add an ENV entry in your Dockerfile:

ENV PYTHONPATH="${PYTHONPATH}:/your/custom/path"

Or set PYTHONPATH in your startup script.

Sign up to request clarification or add additional context in comments.

9 Comments

I tried your suggestion without success, I've edited my original post to include my steps. Could you suggest what I'm doing wrong?
Did you try it with the typo fixed in the string? "${PYTHONPATH}:/your/custom/path"
for one reason or another, this is still just overwriting my PYTHONPATH. Additionally, while this is modifying the ENV variable, my path according to python -c "import sys; for p in sys.path: print(p)" is still unchanged, containing only the old (seemingly overwritten) PYTHONPATH, which none of the changes
The answer is correct, it's probably not working for some people because your're using the wrong path. if your module is named "mymodule" and it located at /src/mymodule then you should have: ENV PYTHONPATH "${PYTHONPATH}:/src"
The OP afsked about adding to PYTHONPATH. If you don’t have that var defined already, then just do ENV PYTHONPATH=/foo
|
14

You're setting the python path correctly, but your command is not being run by a shell, so the environment variable PYTHONPATH is not considered.

chang your CMD from "exec" form to "shell" form:

CMD python control/control_file/job.py


From the Docs:

Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ "sh", "-c", "echo $HOME" ]. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.

Comments

5

Do it in a much simpler way. Add the python path in your .env file as a line in this way.

PYTHONPATH=/app/project_source/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.