连接到Docker容器上的PostgreSQL数据库

fab*_*aia 3 python django postgresql docker

我想在一个独立的Docker容器上运行一个带有PostgreSQL数据库和由Django支持的REST API的应用程序.到目前为止,API已经在连接到SQLite数据库的Docker上运行,但我现在遇到麻烦,我想要连接到PostgreSQL数据库.

Docker的docker-compose.yml文件:

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
Run Code Online (Sandbox Code Playgroud)

Django settings.py(使用基本postgres图像根据文档使用的默认设置):

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'wgomanager',
        'USER': 'postgres',
        'PASSWORD': 'mysecretpassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
Run Code Online (Sandbox Code Playgroud)

当我docker-compose up最终启动应用程序时,抛出此错误:

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

sri*_*igi 5

使用docker-compose时,您可以通过主机名"发现"服务.您的数据库服务是使用标签postgres定义的.将其用作应用程序配置中的主机名.

密码和数据库名称也必须与您的应用配置同步.这是通过postgres服务的环境变量完成的:

services:
  postgres:
    environment:
      - POSTGRES_PASSWORD: "mysecretpassword"
      - POSTGRES_DB: "wgomanager"
  # rest of docker-compose.yml
Run Code Online (Sandbox Code Playgroud)

Reffer到图像文档如何不同ENV.vars会影响服务配置.

  • 请有人给这个人一个奖项,我花了半天的时间试图让数据库运行。谢谢! (2认同)