通过 Docker 设置 Django + Postgres + PgBouncer

通过 Docker 设置 Django + Postgres + PgBouncer

我有一个现有的 Django 应用程序,其中 Django 在 Docker 容器中运行(通过 uvicorn 提供服务),而 Postgres 在另一个 Docker 容器中运行。

在我的settings.py我有

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": <name>,
        "USER": <user>,
        "PASSWORD": <pw>,
        "HOST": "db",
        "PORT": "5432",
   }
}

对于 postgres,我只需要FROM postgres:12.4-alpine在 Dockerfile 中使用它。然后我的 docker-compose.yml 是

services:
  db:
    image: <postgres>
    ...
  site:
    image: <django>
    ...
    depends_on:
      - db

这有效,我试图在此基础上添加 PgBouncer,其中 PgBouncer 在另一个容器中运行,但我发现的所有教程都假设您通过 Heroku 执行此操作。要么网站无法连接到数据库,要么网站直接连接到数据库并跳过 PgBouncer。我现在有的是

PgBouncer Dockerfile

FROM edoburu/pgbouncer:1.12.0
COPY pgbouncer.ini userlist.txt /etc/pgbouncer/
EXPOSE 6432

保镖配置文件

[databases]
<name> = host=db port=5432 dbname=<name>

[pgbouncer]
listen_addr = *
listen_post = 6432
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
unix_socker_dir = /var/run/postgresql
pool_mode = transaction
max_client_conn = 100
default_pool_size = 20

设置.py

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "<name>",
        "USER": "<user>",
        "PASSWORD": "<pw>",
        "HOST": "db",
        'PORT': '', # https://stackoverflow.com/questions/27418264/ideal-settings-for-pgbouncer-with-djangos-conn-max-age suggests this should be empty string instead of 6432?
    }
}

docker-compose

services:
  db:
    image: <postgres>
    ...
  pgbouncer:
    image: <pgbouncer>
    depends_on:
    - db
  site:
    image: <django>
    depends_on:
    - db
    - pgbouncer

相关内容