Question
How to Fix PG::ConnectionBad: Connection Refused in Rails with PostgreSQL
Question
When I run my Rails 4.0 server, I get a PostgreSQL connection error saying the connection was refused on localhost:5432.
The relevant error output is:
Started GET "/" for 127.0.0.1 at 2013-11-06 23:56:36 -0500
PG::ConnectionBad - 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?
could not connect to server: Connection refused
Is the server running on host "localhost" (fe80::1) and accepting
TCP/IP connections on port 5432?
My database.yml looks like this:
development:
adapter: postgresql
encoding: unicode
database: metals-directory_development
pool: 5
username:
password:
template: template0
host: localhost
port: 5432
test: &test
adapter: postgresql
encoding: unicode
database: metals-directory_test
pool: 5
username:
password:
template: template0
host: localhost
port: 5432
staging:
adapter: postgresql
encoding: unicode
database: metals-directory_production
pool: 5
username:
password:
template: template0
host: localhost
production:
adapter: postgresql
encoding: unicode
database: metals-directory_production
pool: 5
username:
password:
template: template0
host: localhost
cucumber:
<<: *test
I am using macOS Mavericks (OS X 10.9). I have already tried reinstalling both PostgreSQL and the pg gem several times. What does this error actually mean, and how can I diagnose and fix it in a Rails app using PostgreSQL?
Short Answer
By the end of this page, you will understand what PG::ConnectionBad with connection refused means in Rails, how Rails uses database.yml to connect to PostgreSQL, and how to systematically check whether PostgreSQL is running, listening on the expected port, and configured correctly for your app.
Concept
PG::ConnectionBad is a PostgreSQL connection error raised by the Ruby pg driver when Rails cannot open a database connection.
In this specific case, connection refused usually means:
- Rails successfully tried to reach the machine and port you specified.
- But nothing was accepting connections there.
- In other words, PostgreSQL is likely not running, not listening on that host/port, or your Rails config points to the wrong place.
This is different from other database errors:
- authentication failed → PostgreSQL is running, but username/password is wrong.
- database does not exist → PostgreSQL is running, but the named database has not been created.
- could not translate host name → the hostname itself is invalid.
- connection refused → the service is not available at that address and port.
In Rails, the connection details typically come from config/database.yml:
adapter: which database system to usedatabase: the database nameusername/password: login credentialshost: where PostgreSQL is runningport: which TCP port to connect to
If Rails says it cannot connect to , the first question is not whether the gem is installed. The first question is:
Mental Model
Think of Rails as a customer trying to enter a building.
hostis the street address.portis the door number.- PostgreSQL is the business inside.
If you get connection refused, Rails reached the address and tried the door, but nobody was there to answer.
That usually means one of these:
- the building is closed → PostgreSQL is not running
- the business moved to another door → PostgreSQL uses a different port
- you went to the wrong address → wrong host in
database.yml
So the fix is usually not rewriting Rails code. It is checking the address, the door, and whether the business is open.
Syntax and Examples
In Rails, a PostgreSQL database connection is commonly configured like this:
development:
adapter: postgresql
encoding: unicode
database: my_app_development
username: myuser
password: secret
host: localhost
port: 5432
A more minimal version often works too:
development:
adapter: postgresql
encoding: unicode
database: my_app_development
pool: 5
If PostgreSQL is installed locally and configured with default settings, Rails may connect without explicitly setting host, port, username, or password.
Example: checking whether PostgreSQL is reachable
From your terminal, try:
psql -h localhost -p 5432 -U postgres -d postgres
Step by Step Execution
Consider this Rails configuration:
development:
adapter: postgresql
database: my_app_development
host: localhost
port: 5432
When you start Rails and load a page, this is roughly what happens:
- Rails boots the application.
- Active Record reads
config/database.yml. - It sees that the
developmentenvironment uses PostgreSQL. - It asks the
pggem to open a connection to:- host:
localhost - port:
5432 - database:
my_app_development
- host:
- The operating system attempts a TCP connection to
localhost:5432. - If PostgreSQL is listening there, the connection continues.
- If nothing is listening there, the OS returns connection refused.
- The
pggem raisesPG::ConnectionBad. - Rails cannot continue because it needs the database connection.
Small troubleshooting trace
Command:
Real World Use Cases
This kind of debugging appears constantly in real software work.
Local app development
A Rails app connects to PostgreSQL on your machine. If the database service is stopped after a reboot, the app fails at startup.
Team onboarding
A developer clones a project, installs dependencies, and runs the app. The code is fine, but PostgreSQL was never started or the local user/database was never created.
CI and test environments
Automated test jobs fail because the database service was not started before running migrations.
Docker or container setups
The app uses localhost, but PostgreSQL actually runs in another container and should be accessed by service name instead.
Production deployment
An app deploy succeeds, but runtime requests fail because the configured database host or port is incorrect.
In all these cases, the main skill is the same: confirm whether the service exists, is reachable, and matches the application configuration.
Real Codebase Usage
In real projects, developers usually treat database connectivity as a configuration and environment problem first.
Common patterns
1. Environment-specific configuration
Different environments use different databases:
development:
adapter: postgresql
database: my_app_development
test:
adapter: postgresql
database: my_app_test
2. Environment variables
Instead of hardcoding credentials, teams often use environment variables:
development:
adapter: postgresql
database: my_app_development
username: <%= ENV['PGUSER'] %>
password: <%= ENV['PGPASSWORD'] %>
host: <%= ENV.fetch('PGHOST', 'localhost') %>
port: <%= ENV.fetch('PGPORT', 5432) %>
Common Mistakes
1. Reinstalling gems before checking whether PostgreSQL is running
A pg gem issue and a database service issue are different things.
If you see connection refused, check the service first:
pg_isready -h localhost -p 5432
2. Assuming localhost always works
Sometimes PostgreSQL is configured to use a Unix socket or a different host.
Broken assumption:
host: localhost
port: 5432
If PostgreSQL is not listening on TCP port 5432, this fails.
3. Forgetting to create the database
Even after PostgreSQL is running, your app database may not exist yet.
Run:
bundle exec rake db:create
bundle exec rake db:migrate
4. Using an invalid or awkward database name
Your config shows:
database: metals-directory_development
Hyphens in PostgreSQL identifiers can be problematic because they often require quoting. Prefer underscores:
Comparisons
| Error / Situation | What it usually means | Most likely next step |
|---|---|---|
connection refused | No service is listening on that host/port | Start PostgreSQL or fix host/port |
password authentication failed | PostgreSQL is running, but credentials are wrong | Fix username/password |
database does not exist | PostgreSQL is running, but the named DB is missing | Create the database |
could not translate host name | Hostname is invalid or DNS failed | Fix host value |
| Configuration choice | Meaning | When to use it |
|---|
Cheat Sheet
# Basic Rails PostgreSQL config
development:
adapter: postgresql
encoding: unicode
database: my_app_development
username: myuser
password: secret
host: localhost
port: 5432
# Check whether PostgreSQL is accepting connections
pg_isready -h localhost -p 5432
# Try connecting manually
psql -h localhost -p 5432 -U postgres -d postgres
# See whether anything is listening on port 5432
lsof -i :5432
# Create app databases
bundle exec rake db:create
bundle exec rake db:migrate
What connection refused means
- Rails reached the host
- But no process accepted the connection on that port
- Usually PostgreSQL is not running, not listening on that port, or
database.ymlis wrong
Good troubleshooting order
- Check that PostgreSQL is installed
- Check that PostgreSQL is running
- Check that it listens on
localhost:5432
FAQ
What does PG::ConnectionBad mean in Rails?
It means the PostgreSQL driver could not establish a connection. The exact reason depends on the rest of the message.
What does connection refused mean for PostgreSQL?
It usually means nothing is listening on the host and port Rails tried to use, such as localhost:5432.
Can this happen even if the pg gem is installed correctly?
Yes. The gem can be installed properly while PostgreSQL itself is stopped or misconfigured.
Should I always set host: localhost in database.yml?
Not always. Some local setups work better without it, especially when using local socket-based connections.
Why is Rails checking the database when I only start the server?
Rails and Active Record often check the database during boot or on the first request because the app needs schema and migration information.
Could the database name be part of the problem?
Yes. If the database does not exist or uses an awkward name such as one with hyphens, it can cause issues. Underscores are safer.
How do I know whether the problem is PostgreSQL or Rails config?
Try connecting manually with psql. If manual connection fails, the issue is probably PostgreSQL service or system configuration rather than Rails code.
What should I check first on macOS?
Mini Project
Description
Build a small Rails-style PostgreSQL connection checker script in Ruby. The project demonstrates how to verify database connectivity outside the full Rails boot process, which helps you separate app problems from service problems.
Goal
Create a Ruby script that attempts to connect to PostgreSQL using the same settings as a Rails app and prints a clear success or failure message.
Requirements
- Read connection settings from variables in the script
- Attempt a PostgreSQL connection using the
pggem - Print a success message if the connection works
- Print the exact error message if the connection fails
Keep learning
Related questions
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.
Convert a Unix Timestamp to Ruby DateTime
Learn how to convert Unix timestamps to Ruby DateTime and Time objects, with examples, differences, pitfalls, and practical Ruby usage.