Python – Connection Error while connecting to PostgreSQL as postgres user

postgresqlpsycopg2python

I am not able connect to PostgreSQL remotely using python and psycopg2:

Here is my code.

>>> import psycopg2
>>> conn_string = "host='localhost' dbname='mydb' user='postgres'"
>>> print "Connecting to database\n     ->%s" % (conn_string)
    Connecting to database
      ->host='localhost' dbname='mydb' user='postgres'
>>> conn = psycopg2.connect(conn_string)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tools/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?

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?

The password is not set for postgres user.

Generally, I can connect to database by running following method on host.

 1. SSH to box
 2. su - postgres
 3. psql
 4. \c mydb

The server runs PostgreSQL 9.1.

Best Answer

You're trying to connect to PostgreSQL on localhost using a script running on your computer, but there's no PostgreSQL server running there.

For this to work, you'd have to ssh to the remote server, then run your Python script there, where the PostgreSQL server is "local" relative to the Python script.

(That's why running psql works - because you're running it on the remote server, where PostgreSQL is "local" relative to psql).

Alternately, you could:

  • Use an SSH tunnel to forward the PostgreSQL port from the local computer to the remote one; or

  • Connect directly over TCP/IP to the remote PostgreSQL server using its host name or IP address, after enabling remote connections on the server.

Note that just putting the server's IP address or host name into the connection string instead of localhost will not work unless you also configure the server to accept remote connections. You must set listen_addresses to listen for non-local connections, add any required firewall rules, set pg_hba.conf to permit connections from remote machines, and preferably set up SSL. All this is covered in the Client Authentication chapter of the PostgreSQL user manual.

You'll probably find an SSH tunnel simpler and easier to understand.

Related Topic