Home > Mobile >  How to make different database settings for local development and using a docker
How to make different database settings for local development and using a docker

Time:07-21

There is a django project that uses dockerisation to run in a production environment. The settings are as follows

docker-compose.yaml

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:8000"
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/gpanel
    depends_on:
      - db
  db:
    image: postgres:13
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=${DATABASE_USER}
      - POSTGRES_PASSWORD=${DATABASE_PASS}
      - POSTGRES_DB=${DATABASE_NAME}

volumes:
  postgres_data:

settings.py

DATABASES = {
    "default": {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': env('DATABASE_NAME'),
        'USER': env('DATABASE_USER'),
        'PASSWORD': env('DATABASE_PASS'),
        'HOST': env('HOST'),
        "PORT": env('PORT'),
    }
}

.env

DATABASE_NAME=pg_db
DATABASE_USER=db_root
DATABASE_PASS=12345
PORT=5432
HOST=db

So in settings.py the host parameter is passed as services name 'db' in the docker-compose.yaml file. This all works when running via docker, but I need to be able to run the project locally without docker. In the standard way for Django using a virtual environment. For this I created locally new database and user. The problem is that when running the command python manage.py runserver

I'm getting error

django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution

CodePudding user response:

You can use an environment variable to specify values that might be different per environment. An approach I like is to make the settings default to the values a developer might use in their day-to-day work

DATABASES = {
    "default": {
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        ...
    }
}

but then in your Compose file override that environment variable to a value that's specific to this deployment

version: '3.8'
services:
  web:
    build: .
    ports:
      - '8000:8000'
    depends_on:
      - db
    environment:
      - DB_HOST=db
  db: { ... }

If you're working in some other environment – maybe your actual production database is a managed cloud database, for example – you can use the environment-variable settings to specify different values that are specific to that deployment, without actually changing your application code.

  • Related