Dockerized nginx/Flask App

Command line arguments in Docker/Nginx/Flask

Posted by Kaushik Raj on November 2, 2015

Flask comes with an in-built webserver. The in-built server is fine for development purpose but not so much for production. There are multiple options available for using a good webserver. nginx is a popular choice.

When using Flask's in-built server, command line arguments can be used to initialize certain values. One can even use `OptionParser` to parse the command line arguments. This is even true when the Flask app is hosted in Docker container.

In case of nginx, where python/Flask is invoked via uwsgi command line arguments is not a viable solution.

To workaround the command line argument limitation, one can use environment variables instead. In the following example, the environment variables are set for the docker container.

$docker run .... -e param1=value1 ....

In the previous case, an environment variable "param1" with "value1" is set for the docker container (at runtime). To read these environment variables in the flask app, use the following code

import os

param1 = os.environ.get("param1", None)
if param1:
    # param1 was set via environment variable
    # use param1

Checkout a working sample at https://github.com/kaushikraj/nginx-flask-env. In this sample, the output of a method is controlled by environment variable.