Connect to a PostgreSQL database on a Docker conta

2019-07-14 18:49发布

问题:

I want to run an application with a PostgreSQL database and a REST API powered by Django on separate Docker containers. So far the API has been running on Docker connecting to a SQLite database, but I'm having trouble now that I want to connect to a PostgreSQL database instead.

Docker's docker-compose.yml file:

version: '2'
services:
    postgres:
        image: postgres
    api:
        build: .
        command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:1337"
        volumes:
            - .:/usr/src/app
        ports:
            - "1337:1337"
        depends_on:
            - postgres

Django's settings.py (using the default settings which the base postgres image works with according to the documentation):

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'wgomanager',
        'USER': 'postgres',
        'PASSWORD': 'mysecretpassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

When I launch the application with docker-compose up eventually this error is thrown:

api_1       |     connection = Database.connect(**conn_params)
api_1       |   File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect
api_1       |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
api_1       | django.db.utils.OperationalError: could not connect to server: Connection refused
api_1       |   Is the server running on host "localhost" (::1) and accepting
api_1       |   TCP/IP connections on port 5432?
api_1       | could not connect to server: Connection refused
api_1       |   Is the server running on host "localhost" (127.0.0.1) and accepting
api_1       |   TCP/IP connections on port 5432?
api_1       |
orchestrator_api_1 exited with code 1

What am I doing wrong?

回答1:

When using docker-compose, you "discover" services via hostname. Your database service is defined with label postgres. Use it as a hostname in your application cofiguration.

Also password and DB name must be in sync with your app config. This is done via environment variables for postgres service:

services:
  postgres:
    environment:
      - POSTGRES_PASSWORD: "mysecretpassword"
      - POSTGRES_DB: "wgomanager"
  # rest of docker-compose.yml

Reffer to image docs on how various env. vars affect service configuration.