Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script is unable to see environment variable injected by Docker

Tags:

python

docker

I have instructed Docker to inject an environment variable called "INJECT_THIS" using two different methodologies (env.list file via 'docker run', and Dockerfile). My Dockerfile's RUN command invokes a Python file (run.py), but the environment variable is not seen by the Python code's os.environ object:

environ({'OLDPWD': '/', 'PATH': '/command:/lsiopy/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'PWD': '/app', 'LC_CTYPE': 'C.UTF-8'})

I've created a reproducible example on Github, but will also paste file contents in this question.

Dockerfile

FROM linuxserver/blender
WORKDIR /app
ENV INJECT_THIS = "inject this"
COPY run.py ./
RUN apt-get update && apt-get -y install python3-pip
CMD ["python3", "-u", "run.py"]

run.py

import os

# Notice that the injected environment variable "INJECT_THIS" is not present.
print('os.environ', os.environ)

env.list

INJECT_THIS="inject this"
like image 974
user2480766 Avatar asked Mar 02 '26 08:03

user2480766


1 Answers

When you do docker inspect <your image name> you will see, there's ENTRYPOINT specified. This entrypoint messes with environment variables.

You can specify your ENTRYPOINT instead of CMD (note I removed the spaces in ENV):

FROM linuxserver/blender
WORKDIR /app
ENV INJECT_THIS="inject this"
COPY run.py ./
RUN apt-get update && apt-get -y install python3-pip
ENTRYPOINT ["python3", "-u", "run.py"]

Then run the docker image:

$ docker run -t <your image name>

Prints:

os.environ environ({'PATH': '/lsiopy/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'HOSTNAME': 'bb98d241500d', 'TERM': 'xterm', 'HOME': '/config', 'LANGUAGE': 'en_US.UTF-8', 'LANG': 'en_US.UTF-8', 'S6_CMD_WAIT_FOR_SERVICES_MAXTIME': '0', 'S6_VERBOSITY': '1', 'S6_STAGE2_HOOK': '/docker-mods', 'VIRTUAL_ENV': '/lsiopy', 'DISPLAY': ':1', 'PERL5LIB': '/usr/local/bin', 'OMP_WAIT_POLICY': 'PASSIVE', 'GOMP_SPINCOUNT': '0', 'START_DOCKER': 'true', 'PULSE_RUNTIME_PATH': '/defaults', 'NVIDIA_DRIVER_CAPABILITIES': 'all', 'LSIO_FIRST_PARTY': 'true', 'TITLE': 'Blender', 'INJECT_THIS': 'inject this'})
like image 109
Andrej Kesely Avatar answered Mar 04 '26 22:03

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!