PostgreSQL in Docker - pg_hba.conf to allow access

2019-06-03 17:50发布

问题:

I want to run PostgreSQL inside a Docker container. I am building my own Docker image, as I want to include PostgreSQL extensions. I should edit the pg_hba.conf configuration file to:

  1. allow access originating from other containers
  2. allow access originating from the host

The first is quite simple: I can add a rule for 172.17.0.0/16 if I am not mistaken.

But how can I approach the second? What does the IP (or range) looks like when the host connects to psql in a container?

Remark: I am starting the container via docker run -p 127.0.0.1:5432:5432, so in theory I could just allow all in pg_hba.conf because the port forwarding is only bound to 127.0.0.1. But I prefer this extra level of security in pg_hba.conf for the situation when I (probably by mistake) run the container via docker run -p 5432:5432. I hope this makes sense.

update

Actually, setting range 172.17.0.0/16 does not seem to be correct. For example, my container had IP 172.18.0.2 in my test. There does not seem to be a consensus on the default range or how to configure that range, according to my investigations so far.

回答1:

check your docker0 bridge interface in your case it might be 172.18.0.0/16

make changes in postgresql.conf path will be same as pg_hba.conf.

listenaddress to "*"

Then in pg_hba.conf add rule as

host all all 172.18.0.0/16 md5.

run the docker with hostip : docker run -p :5432:5432 in this way other containser on same docker n/w can connect aswell as from host,but not from other hosts.