Search code examples
node.jslinuxpostgresqlpg

Can't Connect to Postgresql DB Through Node on Linux


When I try to connect to my database (on a Linux machine) through the command line I'm able to do so just fine:

$ psql -U me -W
Password for user me: 
psql (9.5.7)
Type "help" for help.

me=# 

I can also access it without a password:

    $ psql -U me # this works

However, when I try to connect through the Node library knex (which just uses pg under the hood) I get the following error:

error: password authentication failed for user "me"

I think it has something to do with the combination of Linux users/Postgres users that are setup in Linux, but nothing I've tried has fixed it. I tried altering my connection URL string, but even a correct one (I think) doesn't work:

DATABASE_URL=postgres://localhost:5432/mydb
DATABASE_URL=postgres://me:mypassword@localhost:5432/mydb
# (neither works)

I also tried adding:

host mydb me 127.0.0.1/32 trust

to my /etc/postgresql/9.5/main/pg_hba.conf, but that didn't help either.

I'm pretty sure I just have to somehow tell Node "use this user/password" in the correct way ... but I can't figure out how.

Any help would be appreciated.

EDIT I tried setting my /etc/postgresql/9.5/main/pg_hba.conf to just:

host    all         all         127.0.0.1/32         trust
host    all         al          ::1/128              trust

or in other words "let everyone in without a password". When I psql -W it now accepts any password I enter ... but even so I still get the:

error: password authentication failed for user "me"

error when Node/knex/pg try to connect.


Solution

  • I wound up getting things working by:

    A) Adding a rule to /etc/postgresql/9.5/main/pg_hba.conf to always trust connections over localhost:

    host    all         all         localhost            trust
    

    B) Using a connection URL of:

    postgres://me:mypassword@localhost:5432/mydb