Flask in Docker unable to detect FLASK_ENV

Viewed 1610

I built a flask app and launch it in docker with the Dockerfile as below.

FROM python:3.7

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
WORKDIR /app

CMD export FLASK_ENV=production    
ENTRYPOINT [ "python", "-u", "app.py" ]

In the flask app, I specified some configuration for development & production

if os.environ['FLASK_ENV'] == 'production':
    UPLOAD_URL = '/v1/path/to/production/server'
elif os.environ['FLASK_ENV'] == 'development':
    UPLOAD_URL = '/upload'

However, launching the script caused an error, where the container cannot detect the FLASK_ENV, even though the command was set in the Dockerfile. Can anyone help?

Traceback (most recent call last):
  File "app.py", line 14, in <module>
    import config
  File "/app/config.py", line 14, in <module>
    if os.environ['FLASK_ENV'] == 'production':
  File "/usr/local/lib/python3.7/os.py", line 681, in __getitem__
    raise KeyError(key) from None
KeyError: 'FLASK_ENV'
2 Answers

When you run the resulting image, ENTRYPOINT and CMD are combined into a single command. The CMD you describe will be wrapped in sh -c and then passed as command-line arguments to the program you name as the ENTRYPOINT.

(In your application, try printing out sys.argv. You should see this contain ["app.py", "/bin/sh", "-c", "export ..."].)

If you want to set an environment variable for the image, you need the Dockerfile ENV directive. (You cannot for example RUN export ...; any variables you set this way will be lost at the end of the RUN line.)

ENV FLASK_ENV=production    
CMD ["python", "-u", "app.py"]

Replace : CMD export FLASK_ENV=production

with : ENV FLASK_ENV=production

ENV instruction is also useful for providing environment variables to services you wish to containerize.

Related