ENV in docker file not getting replaced - python

I have a very simple docker file
FROM python:3
WORKDIR /usr/src/app
ENV CODEPATH=default_value
ENTRYPOINT ["python3"]
CMD ["/usr/src/app/${CODEPATH}"]
Here is my container command
docker run -e TOKEN="subfolder/testmypython.py" --name mycontainer -v /opt/testuser/pythoncode/:/usr/src/app/ -t -d python-image:latest
when I see container logs it shows
python3: can't open file '/usr/src/app/${TOKEN}': [Errno 2] No such file or directory

It looks like what you want to do is override the default path to the python file which is run when you launch the container. Rather than passing this option in as an environment variable, you can just pass the path to the file as an argument to docker run, which is the purpose of CMD in your dockerfile. What you set as the CMD option is the default, which users of your image can easily override by passing an argument to the docker run command.
doker run --name mycontainer -v /opt/testuser/pythoncode/:/usr/src/app/ -t -d python-image:latest "subfolder/testmypython.py"

Environment variable name CODEPATH but your setting TOKEN as Environment variable.
could you please try setting CODEPATH as env in following way
doker run -e CODEPATH="subfolder/testmypython.py" --name mycontainer -v /opt/testuser/pythoncode/:/usr/src/app/ -t -d python-image:latest

The way you've split ENTRYPOINT and CMD doesn't make sense, and it makes it impossible to do variable expansion here. You should combine the two parts together into a single CMD, and then use the shell form to run it:
# no ENTRYPOINT
CMD python3 /usr/src/app/${CODEPATH}
(Having done this, better still is to use the approach in #allan's answer and directly docker run python-image python3 other-script-name.py.)
The Dockerfile syntax doesn't allow environment expansion in RUN, ENTRYPOINT, or CMD commands. Instead, these commands have two forms.
Exec form requires you to format the command as a JSON array, and doesn't do any processing on what you give it; it runs the command with an exact set of shell words and the exact strings in the command. Shell form doesn't have any special syntax, but wraps the command in sh -c, and that shell handles all of the normal things you'd expect a shell to do.
Using RUN as an example:
# These are the same:
RUN ["ls", "-la", "some directory"]
RUN ls -la 'some directory'
# These are the same (and print a dollar sign):
RUN ["echo", "$FOO"]
RUN echo \$FOO
# These are the same (and a shell does variable expansion):
RUN echo $FOO
RUN ["/bin/sh", "-c", "echo $FOO"]
If you have both ENTRYPOINT and CMD this expansion happens separately for each half. This is where the split you have causes trouble: none of these options will work:
# Docker doesn't expand variables at all in exec form
ENTRYPOINT ["python3"]
CMD ["/usr/src/app/${CODEPATH}"]
# ["python3", "/usr/src/app/${CODEPATH}"] with no expansion
# The "sh -c" wrapper gets interpreted as an argument to Python
ENTRYPOINT ["python3"]
CMD /usr/src/app/${CODEPATH}
# ["python3", "/bin/sh", "-c", "/usr/src/app/${CODEPATH}"]
# "sh -c" only takes one argument and ignores the rest
ENTRYPOINT python3
CMD ["/usr/src/app/${CODEPATH}"]
# ["/bin/sh", "-c", "python3", ...]
The only real effect of this ENTRYPOINT/CMD split is to make a container that can only run Python scripts, without special configuration (an awkward docker run --entrypoint option); you're still providing most of the command line in CMD, but not all of it. I tend to recommend that the whole command go in CMD, and you reserve ENTRYPOINT for a couple of more specialized uses; there is also a pattern of putting the complete command in ENTRYPOINT and trying to use the CMD part to pass it options. Either way, things will work better if you put the whole command in one directive or the other.

Related

Passing of environment variables with Dockerfile RUN instead of CMD

I have a dockerfile where a few commands need to be executed in a row, not in parallel or asynchronously, so cmd1 finishes, cmd2 starts, etc. etc.
Dockerfile's RUN is perfect for that. However, one of those RUN commands uses environment variables, meaning i'm calling os.getenv at some point. Sadly, it seems like when passing environment variables, be it through the CLI itself or with help of a .env file, only CMD instead of RUN works. but CMD is launching concurrently, so the container executes this command, but goes over right to the next one, which i definitely don't want.
In conclusion, is there even a way to pass environment variables to RUN commands in a dockerfile?
To help understand a bit better, here's an excerpt from my dockerfile:
FROM python:3.8
# Install python dependencies
RUN pip install --upgrade pip
COPY requirements.txt .
RUN pip install -r requirements.txt
# Create working directory
RUN mkdir -p /usr/src/my_directory
WORKDIR /usr/src/my_directory
# Copy contents
COPY . /usr/src/my_directory
# RUN calling method that uses calls os.getenv at some point (THIS IS THE PROBLEM)
RUN ["python3" ,"some_script.py"]
# RUN some other commands (this needs to run AFTER the command above finishes)
#if i replace the RUN above with CMD, this gets called right after
RUN ["python3", "some_other_script.py","--param","1","--param2", "config.yaml"]
Excerpt from some_script.py:
if __name__ == "__main__":
abc = os.getenv("my_env_var") # this is where i get a ReferenceError if i use RUN
do_some_other_stuff(abc)
The .env file I'm using with the dockerfile (or docker-compose):
my_env_var=some_url_i_need_for_stuff
Do not use the exec form of a RUN instruction if you want variable substitution, or use it to execute a shell. From the documentation:
Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, RUN [ "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: RUN [ "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.
This is how I solved my problem:
write a bash script that executes all relevant commands in the nice order that i want to
use ENTRYPOINT instead of CMD or RUN
the bash script will already have the ENV vars, but you can double check with positional arguments passed to that bash script

Setting Docker ENV using python -c "command"

The python modules that I downloaded are inside the user's home directory. I need to set the python path to the user's bin profile. I tried two approaches as shown below in my dockerfile but to no avail. When I check the environment variable in the running container for the first case the PY_USER BIN is $(python -c 'import site; print(site.USER_BASE + "/bin")') and for the second case the PY_USER_BIN is blank. However, when I manually try to export the PY_USER_BIN variable, it works.
ENV PY_USER_BIN $(python -c 'import site; print(site.USER_BASE + "/bin")')
ENV PATH $PY_USER_BIN:$PATH
and
RUN export PY_USER_BIN=$(python -c 'import site; print(site.USER_BASE + "/bin")')
ENV PATH $PY_USER_BIN:$PATH
To me you mix different context of execution.
The ENV command that you use is a Dockerfile command, it is for env variable in the context of docker that would be forwarded to the container.
The RUN command execute a command inside the container, here, export. Whatever is done inside the container stay inside the container and docker will not have access to it.
For me there no point to give as docker ENV variable where python is on the host has they don't share the same file system. If you need to do it on the container context, then run these command inside the container context with standard shell commands.
Try that first by connecting to your container and running a shell inside it, once the commands works, put them in your Dockerfile. That's as simple as that. To do that run it like:
docker run -ti [your container name/tag] [your shell]
if you use sh as shell:
docker run -ti [your container name/tag] sh
Then try your commands.
To me it seems the commands you want would look like that:
RUN export PY_USER_BIN=$(python -c 'import site; print(site.USER_BASE + "/bin")')
RUN export PATH=$PY_USER_BIN:$PATH
Anyway the point of a container is to have a fixed file system, fixed user names and all. So the USER_BIN shall be always in the same path inside the container in 99% case you could has well hardcode it.

Override Dockerfile Entrypoint with Python and parameters/

in my Dockerfile:
ENTRYPOINT ["python3", "start1.py"]
When I run the docker image i want to override it with start2.py with a parameter year=2020. So I run:
docker run -it --entrypoint python3 start2.py year 2020 b43ssssss
It still runs start1.py, what am i doing wrong?
It still runs start1.py, what am i doing wrong?
Because anything pass as CMD with the entrypoint ENTRYPOINT ["python3", "start1.py"] will be pass as an argument to python file start1.py.
You can verify this by doing the following
import argparse, sys
print ("All ARGs",sys.argv[1:])
So the output will be
All ARGs ['start2.py', 'year', '2020', 'b43ssssss']
So Convert entrypoint to python3 only with some default CMD (start1.py) so you will have control which files to run.
ENTRYPOINT ["python3"]
# Default file to run
CMD ["start1.py"]
and then override at run time
docker run -it --rm my_image start2 year 2020 b43ssssss
Now the args should be
All ARGs ['year', '2020', 'b43ssssss']
For a couple of reasons, I tend to recommend using CMD over ENTRYPOINT as a default. This question is one of them: if you need to override the command at run time, it's much easier to do if you specify CMD.
# Change ENTRYPOINT to CMD
CMD ["python3", "start1.py"]
# Run an alternate script
docker run -it myimage \
python3 start2.py year 2020 b43ssssss
# Run a debugging shell
docker run --rm -it myimage \
bash
# Quickly double-check file contents
docker run --rm -it myimage \
ls -l /app
# This is what you're trying to avoid
docker run --rm -it \
--entrypoint /bin/ls \
myimage \
-l app
There is also a useful pattern of using ENTRYPOINT to run a secondary script that does some initial setup (waits for a database, rewrites config files, bootstraps a data store, ...) and then does exec "$#" to launch the CMD. I tend to reserve ENTRYPOINT for this pattern and default to CMD even if I don't specifically need it.
I do not recommend splitting the command with ENTRYPOINT ["python3"]. In the very specific case of wanting to run an alternate Python script it saves one word in the docker run command, but you still need to repeat the script name (unlike the "entrypoint-as-command" pattern) and you still need the --entrypoint option if you want to run something non-Python.

Pass python arguments (argparse) within Docker container

I have a python script that i run with the following command :
python3 scan.py --api_token 5563ff177863e97a70a45dd4 --base_api_url http://101.102.34.66:4242/scanjob/ --base_report_url http://101.102.33.66:4242/ --job_id 42
This works perfectly when I run it on the command line
IN my Dockerfile , I have tried ARG and ENV . none seem to work
#ARG api_token
#ARG username
#ARG password
# Configure AWS arguments
#RUN aws configure set aws_access_key_id $AWS_KEY \
# && aws configure set aws_secret_access_key $AWS_SECRET_KEY \
# && aws configure set default.region $AWS_REGION
### copy bash script and change permission
RUN mkdir workspace
COPY scan-api.sh /workspace
RUN chmod +x /workspace/scan-api.py
CMD ["/python3", "/workspace/scan-api.py"]
so how do i define this flagged argument in docker file ?
And whats the command run when running the image ?
You can do this in two ways as you want to override at run time.
As args to Docker run command
As an ENV to Docker run command
1st is simplest and you will not need to change anything Dockerfile
docker run --rm my_image python3 /workspace/scan-api.py --bar tet --api_token 5563ff177863e97a70a45dd4 --base_api_url http://101.102.34.66:4242/scanjob/ --base_report_url http://101.102.33.66:4242/ --job_id
and my simple script
import sys
print ("All ARGs",sys.argv[1:])
Using ENV you will need to change Dockerfile
I am posting the way for one, you can do this for all args
FROM python:3.7-alpine3.9
ENV API_TOKEN=default_token
CMD ["sh", "-c", "python /workspace/scan-api.py $API_TOKEN"]
So you can override them during run time or have the ability to run with some default value.
docker run -it --rm -e API_TOKEN=new_token my_image
CMD takes exactly the same arguments you used from the command line.
CMD ["/python3", "scan.py", "--api_token", "5563ff177863e97a70a45dd4", "--base_api_url", "http://101.102.34.66:4242/scanjob/", "--base_report_url", "http://101.102.33.66:4242/", "--job_id", "42"]
It's confusing.
You will need to use the SHELL form of ENTRYPOINT (or CMD) in order to have environment variable substitution, e.g.
ENTRYPOINT "/python3","/workspace/scan-api.py","--api-token=${TOKEN}" ...
And then run the container using something of the form:
docker run --interactive --tty --env=TOKEN=${TOKEN} ...
HTH!

Docker ENTRYPOINT with ENV variable and optional arguments

I have a Dockerfile with an ENTRYPOINT that uses an ENV variable. I can't get the ENTRYPOINT structured so the container can also accept additional command line arguments. Here is the relevant part of the Dockerfile:
ARG MODULE_NAME
ENV MODULE_NAME=$MODULE_NAME
ENTRYPOINT /usr/bin/python3 -m ${MODULE_NAME}
That works fine if I just want to launch the container without additional arguments:
docker run my-image
But I need to be able to pass additional command line arguments (e.g., a "--debug" flag) to the python process like this:
docker run my-image --debug
With the form of ENTRYPOINT above, the "--debug" arg is not passed to the python process. I've tried both the exec form and the shell form of ENTRYPOINT but can't get it to work with both the ENV variable and command line args. A few other forms I tried:
This runs but doesn't accept additional args:
ENTRYPOINT ["/bin/bash", "-c", "/usr/bin/python3 -m ${MODULE_NAME}"]
This gives "/usr/bin/python3: No module named ${MODULE_NAME}":
ENTRYPOINT ["/usr/bin/python3", "-m ${MODULE_NAME}"]
This gives "/usr/bin/python3: No module named ${MODULE_NAME}":
ENTRYPOINT ["/usr/bin/python3", "-m", "${MODULE_NAME}"]
It appears it isn't possible to create an ENTRYPOINT that directly supports both variable expansion and additional command line arguments. While the shell form of ENTRYPOINT will expand ENV variables at run time, it does not accept additional (appended) arguments from the docker run command. While the exec form of ENTRYPOINT does support additional command line arguments, it does not create a shell environment by default so ENV variables are not expanded.
To get around this, bash can be called explicitly in the exec form to execute a script that then expands ENV variables and passes command line args to the python process. Here is an example Dockerfile that does this:
FROM ubuntu:16.04
ARG MODULE_NAME=foo
ENV MODULE_NAME=${MODULE_NAME}
RUN apt-get update -y && apt-get install -y python3.5
# Create the module to be run
RUN echo "import sys; print('Args are', sys.argv)" > /foo.py
# Create a script to pass command line args to python
RUN echo "/usr/bin/python3.5 -m $MODULE_NAME \$#" > /run_module.sh
ENTRYPOINT ["/bin/bash", "/run_module.sh"]
Output from the docker image:
$ docker run my-image
Args are ['/foo.py']
$ docker run my-image a b c
Args are ['/foo.py', 'a', 'b', 'c']
Note that variable expansion occurs during the RUN commands (since they are using shell form) so the contents of run_script.py in the image are:
/usr/bin/python3.5 -m foo $#
If the final RUN command is replaced with this:
RUN echo "/usr/bin/python3.5 -m \$MODULE_NAME \$#" > /run_module.sh
then the run_script.sh would contain
/usr/bin/python3.5 -m $MODULE_NAME $#
But output from the running container would be the same since variable expansion will occur at run time. A potential benefit of the second version is that one could override the module to be run at run time without replacing the ENTRYPOINT.
I was able to get the ENV variables resolved inside ENTRYPOINT. The mistake I was making was the ARGs that were used to populate ENV were written before the FROM statement and was hence out of scope for the current docker stage. Once I moved them below FROM, it works great.
My working Dockerfile:
ARG BASE_IMAGE
FROM ${BASE_IMAGE}
ARG NEO4J_USERNAME
ARG NEO4J_URL
ARG NEO4J_PASSWORD
ENV NEO4J_USERNAME=$NEO4J_USERNAME \
NEO4J_URL=$NEO4J_URL \
NEO4J_PASSWORD=$NEO4J_PASSWORD
COPY ./ /
WORKDIR /
ENTRYPOINT python3 -u myscript.py ${NEO4J_URL} ${NEO4J_USERNAME} ${NEO4J_PASSWORD}

Categories