Unable to connect to dockerized postgres on localhost, but remote connection is working

时间:2016-10-20 13:17:53

标签: postgresql docker networking docker-networking

I created docker postgres instance with

docker run -d \
  --name test_db \
  -v data:/var/lib/postgresql/data \
  -e "POSTGRES_PASSWORD=abcdefghij" \
  -e "POSTGRES_USER=testuser" \
  -p 5432:5432 \
  postgres

I can properly connect to this database from other hosts using public server ip, eg.

 psql -U testuser -h 111.111.111.111 -d testuser   // in reality I use proper IP

but if I want to do this on the same host where container is running, it's impossible to connect (it just hangs).

My pg_hba.conf (inside container)

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust    
host    all             all             0.0.0.0/0               md5

Inside postgresql.conf there is a line:

listen_addresses = '*'

Relevant lines of iptables:

$ iptables -L | grep sql
ACCEPT     tcp  --  anywhere             172.19.0.2           tcp dpt:postgresql

Also, it works locally if I use 172.19.0.2 address, but if I use public server IP it just hangs. I have no idea why it's the case. I have my application distributed among many hosts, including one with DB, and I don't want to use other address depending on location. Can somebody help with this?

1 个答案:

答案 0 :(得分:0)

问题很可能不是Docker,而是你所描述的是你的(公司)网络的配置,它将数据包路由到111.111.111.111向默认网关。我怀疑公共IP 111.111.111.111是你的NAT背后的IP。

简称111.111.111.111将不会映射到127.0.0.1,因为绑定是在计算机外部的某处进行的。

您可能希望执行类似iptables redirect all requests to localhost

的操作