Cannot connect to Postgres running on VM from host

2019-03-10 02:38发布

问题:

I have a VM set up with Vagrant that has Postgres running on it (on port 5432), forwarded to port 8280 on the host machine.

I have set the password for the default user and I can connect locally just fine.

I have been trying to set up access from the host machine over port 8280, and I have been unable to get it working with 'MD5' as the trust method.

I have set up postgresql.conf to listen on all addresses:

# postgresql.conf
listen_addresses = '*'

and I have configured pg_hab.conf as follows:

# pg_hab.conf
#TYPE   DATABASE  USER  CIDR-ADDRESS  METHOD
host    all       all   0.0.0.0/0     md5

With all of these settings, if I run the following command from my host machine:

psql --host=127.0.0.1 --port=8280 --username=postgres -d mydb -c '\l'

I am prompted for the password, and then I get:

psql: FATAL:  password authentication failed for user "postgres"

If I then change the METHOD from 'md5' to 'trust' I'm not asked for a password and I can connect as expected. My question is - why can't I connect using 'md5', which is what I want to be able to do? I know that the password I am entering is correct (I have changed it), but for some reason it isn't working.

回答1:

I had the same exact problem. The issue was on the host side, basically the firewall was blocking the port I was using. So this is what I did (I am using OSX Mavericks)

  1. Open the port (Host)

    sudo ipfw add 7000 allow tcp from any to any dst-port 7001

  2. Modify Vagrantfile in order to allow portforwarding

    config.vm.network "forwarded_port", guest: 5432, host: 7001

  3. Edit postgresql.conf (Guest)

    listen_addresses = '*'

  4. Edit pg_hba.conf (you might want to tune this better)

    host all all 0.0.0.0/0 md5

  5. Now, from the host connect normally using the port (in my case 7001) and 'localhost' as host address



回答2:

You need to set a password for the postgres user. It does not have one by default, so you cannot connect.

ALTER USER postgres PASSWORD 'somepassword';

Your local connections probably work because they're using unix sockets with peer authentication, not TCP/IP. If you use:

psql -h 127.0.0.1 -U postgres postgres

on the VM, you'll probably find that that fails too, because you're actually testing TCP/IP based connections now.