Question

On rails console when I tried to connect to postgres database which on machine having ip address suppose xxx.xxx.xxx.xxx.

Gem installed

gem 'dbi'  
sudo apt-get install libpq-dev
gem 'dbd-pg'

I also granted all permission to 'postgres' user and restarted postgres server on this xxx.xxx.xxx.xxx machine

GRANT ALL PRIVILEGES ON DATABASE test TO postgres WITH GRANT OPTION
sudo /etc/init.d/postgresql restart

I am getting following error.

1.9.3p448 :001 > dbh = DBI.connect("DBI:Pg:test:xxx.xxx.xxx.xxx", "postgres", "")

DBI::OperationalError: could not connect to server: Connection refused Is the server running on host "xxx.xxx.xxx.xxx" and accepting TCP/IP connections on port 5432?

from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/dbd-pg-0.3.9/lib/dbd/pg/database.rb:82:in `rescue in initialize'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/dbd-pg-0.3.9/lib/dbd/pg/database.rb:41:in `initialize'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/dbd-pg-0.3.9/lib/dbd/Pg.rb:157:in `new'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/dbd-pg-0.3.9/lib/dbd/Pg.rb:157:in `connect'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/dbi-0.4.5/lib/dbi/handles/driver.rb:33:in `connect'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/dbi-0.4.5/lib/dbi.rb:148:in `connect'
from (irb):1
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.1.1/lib/rails/commands/console.rb:45:in `start'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.1.1/lib/rails/commands/console.rb:8:in `start'
from /home/ashwini/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.1.1/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Please tell me where am going wrong.

Thank you...

Was it helpful?

Solution

Connect with psql and run:

SHOW port;

Betcha the port given isn't 5432. You're probably also on a mac; it's common for mac users to have some binaries linked to the libpq supplied by the operating system (an old PostgreSQL) and some to the libpq of a PostgreSQL they installed themselves. These can have different default socket directories and different TCP port defaults.

You should also:

SHOW listen_addresses ;

and make sure it is *. If it instead says localhost then your PostgreSQL isn't listening on external IPs, only the local loopback. In that case, you should change that in the config file. See the introductory PostgreSQL documentation.

If you've confirmed that PostgreSQL is listening on the IP and port of interest, you should make sure you don't have a firewall blocking connections from outside machines. That would usually result in a timeout, not a connection refused error, though.

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