docker编写Django从localhost访问postgresql



我有一个使用docker compose运行的django应用程序,希望它访问安装在localhost 上的postgres

以下是我遵循的步骤:

1-将host all all 172.17.0.1/16 md5添加到pg_hba.conf

2-在postgresql.conf 中将listen_addresss更改为*

3-将db_host更改为host.docker.internal

4-in-docker-compose.yml向服务添加了额外的主机,所以看起来像这个

services:
web:
extra_hosts:
- "host.docker.internal:host-gateway"

5-重新启动postgresqlsudo systemctl restart postgresql

仍然得到这个错误

could not connect to server: Connection timed out
Is the server running on host "host.docker.internal" (172.17.0.1) and accepting
TCP/IP connections on port 5432?

我做错了什么?

解决了我的问题

首先,你需要知道使用的网络是什么子网

列出所有网络

docker network ls

然后检查你的

docker network inspect network_name

获取类似172.18.0.0/16的子网将子网添加到pghba.conf使ufw接受连接

ufw allow in from subnet