0

I'm setting up django with docker and I can't really get what's the correct way to setup the setting.py

For example, the database I've right now in the setting.py is:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['db_name'],
        'USER': os.environ['db_user'],
        'PASSWORD': os.environ['db_password'],
        'HOST': 'db',
        'PORT': '5432',
    }
}

where db_name, db_user, db_password are set in an enviroment file. db is instead a --link (docker run --link mydb:db ..).

Now, it seems to work, but I'm not really sure I should do like this.

Is this the right way to setup the settings? Especially where the secrete things should be placed, what's the way to call variables in the environment (apparently docker is creating DB_ variables), and when/how to use the linked containers in the settings (with the name or with env variables?).

Is there a way to use 'db' or an enviroment variable as host? I would like to have so beacuse I may specify the db as link or inside the .env file.

Cœur
  • 37,241
  • 25
  • 195
  • 267
EsseTi
  • 4,079
  • 5
  • 36
  • 63

1 Answers1

0

You can pass environment variable to containers with the -e flag:

docker run -e VAR_NAME=VAR_VALUE ...

so, if your db value is accessible to the process running the container, you could do something along those lines:

export DB=db
docker run -e db_host=$DB --link mydb:$DB mycontainer

and then in Django settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['db_name'],
        'USER': os.environ['db_user'],
        'PASSWORD': os.environ['db_password'],
        'HOST': os.environ['db_host'], # 'db' in this example 
        'PORT': '5432',
    }
}

Depending on your set up, you could also load the whole .env file instead of exporting the single DB variable (look at the the answers to this question for an explanation of how do it). In this way - assuming that your app takes care of loading the env file for itself - you wouldn't have to pass an environment variable to the container, since the app will rely on the .env file for getting the value.

# Assuming DB=db in the .env file
docker run -e --link mydb:$DB mycontainer
Community
  • 1
  • 1
Railslide
  • 5,344
  • 2
  • 27
  • 34