PostgreSQL error: could not connect to database template1: could not connect to server: No such file or directory

Posted on Feb 2, 2023

Question

I need to create database.

First I run: sudo su - postgres, then: createdb test

And I keep getting this error:

createdb: could not connect to database template1: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"

This is unexpected, I have never encountered any problems with psql, but this time I don't get what is wrong. And there is no external server, I am connected locally.

I am running on Ubuntu.

Answer

The error means that the Postgres server is not running. Try starting it:

sudo systemctl start postgresql

I believe the service name is postgresql, but if that doesn’t work, try typing

sudo systemctl start postgres

and pressing tab to auto-complete.

Make sure that the server starts on boot:

sudo systemctl enable postgresql