rivar_
rivar_

Reputation: 375

Passing args to python script inside Dockerfile

I would like to be able to pass Args from docker-compose file > dockerfile and later to CMD/ENTRYPOINT that runs a python script which accepts parameters

ARG INSTANCE_NUM
ENV INSTANCE_NUM=$INSTANCE_NUM
RUN echo $INSTANCE_NUM
ARG TOTAL_INSTANCES
ENV TOTAL_INSTANCES=$TOTAL_INSTANCES
RUN echo $TOTAL_INSTANCES

CMD ["python", "test.py", "$INSTANCE_NUM", 
"$TOTAL_INSTANCES"]

While running build, RUN echo $INSTANCE_NUM and RUN echo $TOTAL_INSTANCES prints the actual value that is set in the docker-compose file but

the current result is that the python script accepts the ARGS as is, without accepting the value given in docker-compose file. e.g If printed out its str $INSTANCE_NUM or str $TOTAL_INSTANCES I would like to be able to get the actual value I've set in the docker-compose file for the ARG which is passed.

Please assist, maybe i'm missing here something or just did not understand properly.

Thanks!

Upvotes: 4

Views: 5949

Answers (1)

Adiii
Adiii

Reputation: 59966

Docker will not treat them as an Environment variable the way you passed in the CMD because CMD run as docker command and will not involve shell, so no shell means no variable interpolation, so it will not work until you specify to execute as a shell.

ARG INSTANCE_NUM
ENV INSTANCE_NUM=$INSTANCE_NUM
RUN echo $INSTANCE_NUM
ARG TOTAL_INSTANCES
ENV TOTAL_INSTANCES=$TOTAL_INSTANCES
RUN echo $TOTAL_INSTANCES

CMD ["sh", "-c", "python test.py $INSTANCE_NUM $TOTAL_INSTANCES"]

Second thing you can not use build args in CMD as CMD is supposed to run at boot time.

So it will not work and it will just print as it is.

ARG INSTANCE_NUM
RUN echo $TOTAL_INSTANCES
CMD ["python","$INSTANCE_NUM"]

To expend variable, need to specify shell in CMD.

ARG INSTANCE_NUM
ENV INSTANCE_NUM=$INSTANCE_NUM
CMD ["sh", "-c", "echo $INSTANCE_NUM; python $INSTANCE_NUM"]

Build with ARGs or you can overide at run time.

 docker build --build-arg INSTANCE_NUM=testargs -t mypy .

RUN

docker run -it mypy

Or you now can override at run time if you missed at build time.

 docker run  -e INSTANCE_NUM=overide_value -it mypy 

The same thing can be done with docker-compose

version: "3"
services:
 mongo:
   image: mypy
   environment:
     - INSTANCE_NUM=overide_from_compose

Upvotes: 8

Related Questions