[ruby-on-rails] Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

Before anything, please note that I have found several similar questions on Stack Overflow and articles all over the web, but none of those helped me fix my issue:

Now, here is the issue:

  • I have a Rails app that works like a charm.
  • With my collaborator, we use GitHub to work together.
  • We have a master and an mvp branches.
  • I recently updated my git version with Homebrew (Mac).
  • We use Foreman to start our app locally.

Now, when I try to launch the app locally, I get the following error:

PG::ConnectionBad at /
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?

I tried to reboot my computers several times.

I also checked the content of /usr/local/var/postgres:

PG_VERSION      pg_dynshmem     pg_multixact    pg_snapshots    pg_tblspc       postgresql.conf
base            pg_hba.conf     pg_notify       pg_stat         pg_twophase     postmaster.opts
global          pg_ident.conf   pg_replslot     pg_stat_tmp     pg_xlog         server.log
pg_clog         pg_logical      pg_serial       pg_subtrans     postgresql.auto.conf

As you can see, there is no postmaster.pid file in there.

Any idea how I could fix this?

The answer is


For Docker users: In my case it was caused by excessive docker image size. You can remove unused data using prune command:

docker system prune --all --force --volumes

Warning: as per manual (docker system prune --help):

This will remove:

  • all stopped containers
  • all networks not used by at least one container
  • all dangling images
  • all dangling build cache

In my case I forgot to change the database from postgres (on my production) back to sqlite3 which I was using for development.


Step 1:

cd /etc/postgresql/12/main/

open file named postgresql.conf

sudo nano postgresql.conf

add this line to that file

listen_addresses = '*'

then open file named pg_hba.conf

sudo nano pg_hba.conf

and add this line to that file

host  all  all 0.0.0.0/0 md5

It allows access to all databases for all users with an encrypted password

restart your server

sudo /etc/init.d/postgresql restart

In my case

  1. I have changed the port in postgresql.conf file
  2. and restart postgresql services in

Run => service.msc => Restart

  1. now retry

First I tried

lsof -wni tcp:5432 but it doesn't show any PID number.

Second I tried

Postgres -D /usr/local/var/postgres and it showed that server is listening.

So I just restarted my mac to restore all ports back and it worked for me.


This worked in my case:

brew uninstall postgresql
rm -fr /usr/local/var/postgres/
brew install postgresql

This worked for me: run

sudo lsof -i :<port_number>

after that it will display the PID which is currently attached to the process.

After that run sudo kill -9 <PID>

if that doesn't work, try the solution offered by user8376606 it would definitely work!


I had almost just as same error with my Ruby on Rails application running postgresql(mac). This worked for me:

brew services restart postgresql

run postgres -D /usr/local/var/postgres and you should see something like:

 FATAL:  lock file "postmaster.pid" already exists
 HINT:   Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"?

Then run kill -9 PID in HINT

And you should be good to go.


It also gives the same error if you just stop your PostgreSQL app. You just need to start it again. (PostgreSQL 11)


The postgresql server might be down and the solution might be as simple as running:

sudo service postgresql start

which fixed the issue for me.


If you want to restart Postgresql on Linux, then you have to use the following command.

/etc/init.d/postgresql restart


I often encounter this problem on windows,the way I solved the problem is Service - Click PostgreSQL Database Server 8.3 - Click the second tab "log in" - choose the first line "the local system account".


I have faced the same issue and I was unable to start the postgresql server and was unable to access my db even after giving password, and I have been doing all the possible ways.

This solution worked for me,

For the Ubuntu users: Through command line, type the following commands:

1.service --status-all (which gives list of all services and their status. where "+" refers to running and "-" refers that the service is no longer running)

check for postgresql status, if its "-" then type the following command

2.systemctl start postgresql (starts the server again)

refresh the postgresql page in browser, and it works

For the Windows users:

Search for services, where we can see list of services and the right click on postgresql, click on start and server works perfectly fine.


This could be caused by the pid file created for postgres which has not been deleted due to unexpected shutdown. To fix this, remove this pid file.

  1. Find the postgres data directory. On a MAC using homebrew it is /usr/local/var/postgres/, other systems it might be /usr/var/postgres/

  2. Remove pid file by running:

    rm postmaster.pid
    
  3. Restart postgress. On Mac, run:

    brew services restart postgresql
    

I resolved the issue via this command

pg_ctl -D /usr/local/var/postgres start

At times, you might get this error

pg_ctl: another server might be running; trying to start server anyway

So, try running the following command and then run the first command given above.

pg_ctl -D /usr/local/var/postgres stop

I encountered a similar problem when I was trying to connect my Django application to PostgreSQL database.

I wrote my Dockerfile with instructions to setup the Django project followed by instructions to install PostgreSQL and run Django server in my docker-compose.yml.

I defined two services in my docker-compose-yml.

services:
  postgres:
    image: "postgres:latest"
    environment:
      - POSTGRES_DB=abc
      - POSTGRES_USER=abc
      - POSTGRES_PASSWORD=abc
    volumes:
      - pg_data:/var/lib/postgresql/data/
  django:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8004
    volumes:
      - .:/app
    ports:
      - 8004:8004
    depends_on:
      - postgres 

Unfortunately whenever I used to run docker-compose up then same err. used to pop up.

And this is how my database was defined in Django settings.py.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'abc',
        'USER': 'abc',
        'PASSWORD': 'abc',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS': {
            'client_encoding': 'UTF8',
        },
    }
} 

So, In the end I made use of docker-compose networking which means if I change the host of my database to postgres which is defined as a service in docker-compose.yml will do the wonders.

So, Replacing 'HOST': '127.0.0.1' => 'HOST': 'postgres' did wonders for me.

After replacement this is how your Database config in settings.py will look like.

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'abc',
            'USER': 'abc',
            'PASSWORD': 'abc',
            'HOST': 'postgres',
            'PORT': '5432',
            'OPTIONS': {
                'client_encoding': 'UTF8',
            },
        }
    } 

Wild stab in the dark: You're on a machine with an IPv6 resolver where localhost defaults to the IPv6 address ::1, but listen_addresses in postgresql.conf is set to 127.0.0.1 or 0.0.0.0 not * or you're using an older PostgreSQL built with a C library that doesn't have transparent IPv6 support.

Change listen_addresses to localhost and make sure localhost resolves to both the IPv4 and IPv6 addresses, or set it to ::1, 127.0.0.1 to explicitly specify both IPv4 and IPv6. Or just set it to * to listen on all interfaces. Alternately, if you don't care about IPv6, connect to 127.0.0.1 instead of localhost.

See this Google search or this Stack Overflow search for more information.

(Posting despite my close-vote because I voted the question for migration).


Most likely it's because your system shutdown unexpectedly

Try

postgres -D /usr/local/var/postgres

You might see

FATAL:  lock file "postmaster.pid" already exists
HINT:  Is another postmaster (PID 449) running in data directory "/usr/local/var/postgres"?

Then try

kill -9 PID

example

kill -9 419

And it should start postgres normally


Examples related to ruby-on-rails

Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Where do I put a single filter that filters methods in two controllers in Rails Empty brackets '[]' appearing when using .where How to integrate Dart into a Rails app Rails 2.3.4 Persisting Model on Validation Failure How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Rails: Can't verify CSRF token authenticity when making a POST request Uncaught ReferenceError: React is not defined

Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to postgresql

Subtracting 1 day from a timestamp date pgadmin4 : postgresql application server could not be contacted. Psql could not connect to server: No such file or directory, 5432 error? How to persist data in a dockerized postgres database using volumes input file appears to be a text format dump. Please use psql Postgres: check if array field contains value? Add timestamp column with default NOW() for new rows only Can't connect to Postgresql on port 5432 How to insert current datetime in postgresql insert query Connecting to Postgresql in a docker container from outside

Examples related to ruby-on-rails-3

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? rake assets:precompile RAILS_ENV=production not working as required How do you manually execute SQL commands in Ruby On Rails using NuoDB Check if record exists from controller in Rails How to restart a rails server on Heroku? How to have a drop down <select> field in a rails form? "Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application Adding a simple spacer to twitter bootstrap How can I change cols of textarea in twitter-bootstrap? Rails: FATAL - Peer authentication failed for user (PG::Error)

Examples related to ruby-on-rails-4

Uninitialized Constant MessagesController Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? NameError: uninitialized constant (rails) How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1) ActionController::UnknownFormat Add a reference column migration in Rails 4 PG::ConnectionBad - could not connect to server: Connection refused Auto-loading lib files in Rails 4 cannot load such file -- bundler/setup (LoadError) Rails 4: how to use $(document).ready() with turbo-links