Docker

從在 docker 容器中執行的 django 應用程序連接到主機 postgresql

  • November 25, 2022

我正在嘗試從在 docker 容器中執行的 django 應用程序連接到我的主機 postgresql 伺服器(版本 14)。

這是我的設置

docker-compose.yml:

version: '3'
services: 
  web:
    build: .
      container_name: dm-api
    volumes: 
      - .:/code
      - static:/code/dojo_manager/static
      - media:/code/dojo_manager/media
    expose: 
      - 8080
    extra_hosts:
      - "database:172.17.0.1"
    command: bash -c "systemctl restart cron && python manage.py collectstatic --no input && python manage.py migrate && gunicorn --workers=3 dojo_manager.wsgi -b 0.0.0.0:8080"
  nginx:
    restart: always
    build: ./nginx/
    volumes: 
       - ./nginx/:/etc/nginx/conf.d
       - ./logs/:/code/logs
       - static:/code/static
       - media:/code/media
    ports: 
       - "1221:80"
    links:
       - web  
volumes: 
  media:
  static:  

pg_hba.conf:

# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
host    all             all             172.17.0.0/16           md5
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer

配置:

docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
   inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
   inet6 fe80::42:41ff:fe7c:b9e9  prefixlen 64  scopeid 0x20<link>
   ether 02:42:41:7c:b9:e9  txqueuelen 0  (Ethernet)
   RX packets 40651  bytes 6850716 (6.8 MB)
   RX errors 0  dropped 0  overruns 0  frame 0
   TX packets 51087  bytes 570351402 (570.3 MB)
   TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

postgresql.conf:

listen_addresses = '*'

但是當我啟動容器時出現錯誤:

django.db.utils.OperationalError: connection to server at "database" (172.17.0.1), port 5432 failed: FATAL:  no pg_hba.conf entry for host "172.19.0.2", user "dtuser", database "dtdb", SSL encryption
connection to server at "database" (172.17.0.1), port 5432 failed: FATAL:  no pg_hba.conf entry for host "172.19.0.2", user "dtuser", database "dtdb", no encryption

我嘗試了各種線上資源和文件。但是,我似乎無法執行連接。

非常感謝任何提示/幫助。最佳班尼迪克特

該錯誤消息中的問題確實存在。主機 172.19.0.2 沒有 hba 條目。您只允許來自 172.16.0.0/16 的連接。你可能想要的是 172.16.0.0/12

引用自:https://serverfault.com/questions/1116592