Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

python - Connect to a PostgreSQL database on a Docker container

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...