Postgres Docker - 无法从远程服务器

时间:2016-08-10 18:46:53

标签: postgresql docker psql

我正在使用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?

在我的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

我已根据说明here修改了我的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

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

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

1 个答案:

答案 0 :(得分:5)

您似乎并未真正发布公开的端口。

而不是:

expose:
  - 5432

使用:

ports:
 - "5432:5432"

expose docs:

  

暴露端口而不将它们发布到主机 - 他们会   只能访问链接服务。只有内部端口可以   指定。

相关问题