1

I have the below Dockerfile where I need to interpolate the filename to be run.

ARG PYTHON_VERSION=3.7-alpine

# Use the python image as the base image
FROM python:${PYTHON_VERSION}

# set environment to run
ENV ENVIRONMENT={ENVIRONMENT:-"prod"}

# Copy the python files
COPY requirements.txt /app/
COPY prod.py dev.py requirements.txt /app/

# Set the working directory 
WORKDIR /app

# Install the dependencies 
RUN pip install -r requirements.txt

# Set the command to run the python file when the container is started
CMD ["python", "${ENVIRONMENT}.py"]

But when I build the image and run it, I get the following error:

python: can't open file '${ENVIRONMENT}.py': [Errno 2] No such file or directory

Why this is not interpolated correctly? Can someone help me with this?

Jananath Banuka
  • 2,951
  • 8
  • 57
  • 105
  • You may be missing the declaration of the environment variable `ENVIRONMENT` during the build – Jib Dec 20 '22 at 11:21
  • I would advise you to use a docker-compose file which selects the command to be executed by the container based on the environment variable instead .. – Jib Dec 20 '22 at 11:23
  • 1
    You could use the shell form without JSON-array syntax `CMD ./$ENVIRONMENT.py`, but it might be easier to just override the entire command when you run the image `docker run your-image ./dev.py`. – David Maze Dec 20 '22 at 11:59

1 Answers1

0

I think your best bet is to have something like a run.py which reads the $ENVIRONMENT variable and then loads the correct file. Or, depending on how far dev.py and prod.py diverge, they could even be one file after all.

lxg
  • 12,375
  • 12
  • 51
  • 73
  • So I can't use string interpolation here? – Jananath Banuka Dec 20 '22 at 11:26
  • I don’t think you can use the extrapolation syntax, but I don’t have a source to support that. There are apparently some ways to achieve what you want by decomposition, or by wrapping into another shell, see here: https://stackoverflow.com/questions/40454470/how-can-i-use-a-variable-inside-a-dockerfile-cmd – lxg Dec 20 '22 at 11:41