Django connection to postgres by docker-compose

后端 未结 2 1206
感动是毒
感动是毒 2020-12-11 01:54

My django project cannot connect to postgres database container. What I should to do?

It crashes on commands python manage.py collectstatic --noinput &&

相关标签:
2条回答
  • 2020-12-11 02:45

    Each container in docker by default gets its own hostname and IP. When compose spins up the containers for you, it also places all of the containers on a network by default to permit DNS based discovery.

    What this means is that your database is not reachable on localhost, but you can reach it by the service name "db". Change this line in your settings.py:

        'HOST': 'localhost',
    

    to:

        'HOST': 'db',
    
    0 讨论(0)
  • 2020-12-11 02:45

    Here's what worked for me:

    in compose:

    version: '3.7'
    services: 
      web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8000
        volumes: 
            - .:/code
        ports: 
            - 8000:8000
        environment: 
            - DB_HOST=db
            - DB_NAME=web
            - DB_USER=postgres
            - DB_PASSWORD=postgres
    
        depends_on: 
            - db
    
      db:
        image: postgres:12-alpine
        volumes: 
            - postgres_data:/var/lib/postgresql/data/
        environment: 
            - POSTGRES_DB=web
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=postgres
    volumes:
       postgres_data:
    

    in settings:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME'),
        'USER':os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST':os.environ.get('DB_HOST'),
        'PORT':5432,
     }
    }
    
    0 讨论(0)
提交回复
热议问题