Postgres Docker - 无法从远程服务器连接

cle*_*ssi 0 postgresql psql docker

我正在使用postgres:9.5.3 docker image.我正在启动容器,然后尝试从远程主机连接到psql数据库,但每次失败并出现错误:

psql: could not connect to server: Connection refused
Is the server running on host "172.18.0.2" and accepting
TCP/IP connections on port 5432?
Run Code Online (Sandbox Code Playgroud)

在我的docker-compose文件中,我正在挂载pg_hba.conf.这是我的docker-compose文件:

services:
    db:
      networks:
        - test
      image: postgres:9.5.3
      expose:
        - 5432
      volumes:
        - ./pgdata/:/var/lib/postgresql/data
        - ./pg_hba.conf/:/var/lib/postgresql/data/pg_hba.conf
Run Code Online (Sandbox Code Playgroud)

我已经修改了我的pg_hba.conf文件,以根据此处的说明接受来自所有主机的远程连接.我的pg_hba.conf如下:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             0.0.0.0/0               trust
# IPv6 local connections:
host    all             all             ::0/0                   trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                trust
#host    replication     postgres        127.0.0.1/32            trust
#host    replication     postgres        ::1/128                 trust

host all all 0.0.0.0/0 md5
Run Code Online (Sandbox Code Playgroud)

我的postgresql.conf也有以下行: listen_addresses = '*'

当我尝试从主机连接数据库时,我正在运行容器,它成功连接.但是当我尝试使用该命令从任何远程计算机进行连接时psql -h 172.18.0.2 -U postgres -d postgres -p 5432,它会给出连接错误,这意味着远程连接无法正常工作.有了所有这些设置,我希望它可以连接.我在这里错过了什么?

ldg*_*ldg 5

您似乎并没有实际发布暴露的端口.

代替:

expose:
  - 5432
Run Code Online (Sandbox Code Playgroud)

使用:

ports:
 - "5432:5432"
Run Code Online (Sandbox Code Playgroud)

expose 文档:

暴露端口而不将它们发布到主机 - 它们只能被链接服务访问.只能指定内部端口.