Docker - make my application use secrets instead of env. vars

2.3k Views Asked by At

My Django application uses at lot of environment variables, around 35 in total. Currently all these are handeld by a .env file that I source before I start my application stack. I guess that I don't have to point out that this is by far a very insecure way especially if it's about secret key's in production ...

Now my problem is that I don't really understand how to make the switch from a .env file to secrets, as I don't understand how to process the secrets at my container. For example, Django uses a connection string to connect with my MySQL database, see below:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
        'NAME': env.str('MYSQL_DB'),
        'USER': env.str('MYSQL_USER'),
        'PASSWORD': env.str('MYSQL_PWD'),
        'HOST': env.str('MYSQL_HOST'),
        'PORT': env.str('MYSQL_PORT'),
    }
}

Most of the time I use "env.str" to fetch my vars that I pass to the container at start. So how can I make my Django application work with docker secrets and if possible stay with fetching vars the way like shown above? Is it maybe possible to load all needed vars on start at my docker-entrypoint.sh, and if yes, how can this be accomplished?

I already came acorss this solution:

if [ -f /run/secrets/MYSQL_PWD ]; then
  export MYSQL_PWD=$(< /run/secrets/MYSQL_PWD)
fi

if [ -f /run/secrets/MYSQL_USER ]; then
  export MYSQL_USER=$(< /run/secrets/MYSQL_USER)
fi

Does that makes sense to trigger on startup to gets my env vars in place? See: https://github.com/grafana/grafana-docker/issues/149

Thanks for reading

1

There are 1 best solutions below

3
On BEST ANSWER

One option is to create one secret with your file then use the source commande to load all your environment variables all at once.

docker secret create mysecret <path_to_your_env_file>

source /run/secrets/mysecret  // in your entrypoint.sh