Question

I'm having an issue with PostgreSQL

anytime I run

psql -h localhost

I get

psql: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Was it helpful?

Solution

A. First make sure PostgreSQL server has been started to remote server.

# /etc/init.d/postgresql start

If it is running and you get above error, you need to add enable TCP/IP support. By default, the PostgreSQL server only allows connections to the database from the local machine or localhost. This is a security feature.

Step # 1: Allow remote IP address to access PostgreSQL

You need to open file called /var/lib/pgsql/data/pg_hba.conf. Login as postgres user using su command:

$ su - postgres
$ vi /var/lib/pgsql/data/pg_hba.conf

Now append following line. Let us say you would like to give access to 192.168.1.0/24 network:

host all all 192.168.1.0 255.255.255.0 trust

Please replace 192.168.1.0 and 255.255.255.0 to reflect the actual network IP address range of the clients system in your own network.

Save close the file.

Step # 2: Allow communication over TCP/IP

You need to open PostgreSQL configuration file /var/lib/pgsql/data/postgresql.conf

$ vi /var/lib/pgsql/data/postgresql.conf

Now bind and open TCP/IP port by setting tcpip_socket to true:

tcpip_socket = true

Save and close the file.

Step # 3: Restart PostgreSQL server

Restart the PostgreSQL server with the following command

# /etc/init.d/postgresql restart

This will open default port 5432.

Step # 4: Test your setup

Use psql command from client system as follows:

psql -h PostgreSQL-IP-ADDRESS -U USERNAME -d DATABASENAME

Connect to remote server by IP address 192.168.1.5 and login using vivek user to connect to sales database, use:

$ psql -h 192.168.1.5 -U vivek -d sales

Where,

-h 192.168.1.5 : Specifies the host name of the machine or IP address (192.168.1.5) on which the server is running.

-U vivek : Connect to the database as the vivek username instead of the default. You must have account and permission to connect as vivek user.

-d sales : Specifies the name of the database (sales) to connect to.

OTHER TIPS

For anyone reading this and using Postgres.app, you may need host: localhost in your database.yml. http://postgresapp.com/documentation#toc_3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top