Andrew Graham-Yooll
Andrew Graham-Yooll

Reputation: 2258

Change the PYTHONPATH in a docker container in docker-compose file

I have an application in a docker container whose entry point is defined as

ENTRYPOINT ["/usr/local/bin/gunicorn", "--pythonpath=`$PWD`/.."]

Then, I have three container processes which use that container and entry point to serve my files from the app. Everything fine there.

I now am trying to start another container process that over rides the gunicorn command. I want it to run a python3 process with the command

entrypoint: ["python3", "/crm/maintenance/maintenance.py"]

in the docker-compose.yml file.

The issue is when I run docker-compose up -d with the above entrypoint, all containers run fine except for the one running the python process.

The error I get is:

Traceback (most recent call last):
File "/crm/maintenance/maintenance.py", line 6, in <module>
    from crm.sms_system.answer_send import AnswerSender
ImportError: No module named 'crm'

I attribute this error to the python path that remains incorrect. For the Entrypoint defined in the docker file I have the "--pythonpath=$PWD/.." flag. But this cannot transfer over to python3.

Instead I have tried a number of things:

  1. In dockerfile ENV PYTHONPATH=$PWD/..
  2. In docker-compose.yml entrypoint: ["PYTHONPATH=/..","python3", "/crm/maintenance/maintenance.py"]
  3. In docker-compose.yml entrypoint: ["PYTHONPATH=$PWD/..","python3", "/crm/maintenance/maintenance.py"]. This does not work since the PWD is executed from where you run the docker-compose up command from not in the container.

How can I change the PYTHONPATH at run time in a container from the docker-compose file?

Upvotes: 3

Views: 11103

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146540

You need to use $$ to escape the environment variable parsing for docker-compose. Here is a sample file which worked for me

version: '2'
services:
  python:
    image: python:3.6
    working_dir: /usr/local
    command: bash -c "PYTHONPATH=$$PWD/.. python3 -c 'import sys; print(sys.path)'"

$ docker-compose up
Recreating test_python_1
Attaching to test_python_1
python_1  | ['', '/usr', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages']
test_python_1 exited with code 0

Upvotes: 4

Related Questions