Psql ошибка подключиться к серверу через сокет

I experienced this issue when working with PostgreSQL on Ubuntu 18.04.

I checked my PostgreSQL status and realized that it was running fine using:

sudo systemctl status postgresql

I also tried restarting the PotgreSQL server on the machine using:

sudo systemctl restart postgresql

but the issue persisted:

psql: 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"?

Following Noushad’ answer I did the following:

List all the Postgres clusters running on your device:

pg_lsclusters

this gave me this output in red colour, showing that they were all down and the status also showed down:

Ver Cluster Port Status Owner    Data directory              Log file
10  main    5432 down   postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log
11  main    5433 down   postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
12  main    5434 down   postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

Restart the pg_ctlcluster for one of the server clusters. For me I restarted PG 10:

sudo pg_ctlcluster 10 main start

It however threw the error below, and the same error occurred when I tried restarting other PG clusters:

Job for postgresql@10-main.service failed because the service did not take the steps required by its unit configuration.
See "systemctl status postgresql@10-main.service" and "journalctl -xe" for details.

Check the log for errors, in this case mine is PG 10:

sudo nano /var/log/postgresql/postgresql-10-main.log

I saw the following error:

2020-09-29 02:27:06.445 WAT [25041] FATAL:  data directory "/var/lib/postgresql/10/main" has group or world access
2020-09-29 02:27:06.445 WAT [25041] DETAIL:  Permissions should be u=rwx (0700).
pg_ctl: could not start server
Examine the log output.

This was caused because I made changes to the file permissions for the PostgreSQL data directory.

I fixed it by running the command below. I ran the command for the 3 PG clusters on my machine:

sudo chmod -R 0700 /var/lib/postgresql/10/main
sudo chmod -R 0700 /var/lib/postgresql/11/main
sudo chmod -R 0700 /var/lib/postgresql/12/main

Afterwhich I restarted each of the PG clusters:

sudo pg_ctlcluster 10 main start
sudo pg_ctlcluster 11 main start
sudo pg_ctlcluster 12 main start

And then finally I checked the health of clusters again:

pg_lsclusters

this time around everything was fine again as the status showed online:

Ver Cluster Port Status Owner    Data directory              Log file
10  main    5432 online postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log
11  main    5433 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
12  main    5434 online postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

That’s all.

I hope this helps

Resetting PostgreSQL

My original answer only included the troubleshooting steps below, and a workaround. I now decided to properly fix it via brute force by removing all clusters and reinstalling, since I didn’t have any data there to keep. It was something along these lines, on my Ubuntu 21.04 system:

sudo pg_dropcluster --stop 12 main
sudo pg_dropcluster --stop 14 main
sudo apt remove postgresql-14
sudo apt purge postgresql*
sudo apt install postgresql-14

Now I have:

$ pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
14  main    5432 online postgres /var/lib/postgresql/14/main /var/log/postgresql/postgresql-14-main.log

And sudo -u postgres psql works fine. The service was started automatically but it can be done manually with sudo systemctl start postgresql.

Incidentally, I can recommend the PostgreSQL docker image, which eliminates the need to bother with a local installation.

Troubleshooting

Although I cannot provide an answer to your specific problem, I thought I’d share my troubleshooting steps, hoping that it might be of some help. It seems that you are on Mac, whereas I am running Ubuntu 21.04, so expect things to be different.

This is a client connection problem, as noted by section 19.3.2 in the docs.

The directory in my error message is different:

$ sudo su postgres -c "psql"
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
        Is the server running locally and accepting connections on that socket?

I checked what unix sockets I had in that directory:

$ ls -lah /var/run/postgresql/
total 8.0K
drwxrwsr-x  4 postgres postgres  160 Oct 29 16:40 .
drwxr-xr-x 36 root     root     1.1K Oct 29 14:08 ..
drwxr-s---  2 postgres postgres   40 Oct 29 14:33 12-main.pg_stat_tmp
drwxr-s---  2 postgres postgres  120 Oct 29 16:59 14-main.pg_stat_tmp
-rw-r--r--  1 postgres postgres    6 Oct 29 16:36 14-main.pid
srwxrwxrwx  1 postgres postgres    0 Oct 29 16:36 .s.PGSQL.5433
-rw-------  1 postgres postgres   70 Oct 29 16:36 .s.PGSQL.5433.lock

Makes sense, there is a socket for 5433 not 5432. I confirmed this by running:

$ pg_lsclusters
Ver Cluster Port Status                Owner    Data directory              Log file
12  main    5432 down,binaries_missing postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log
14  main    5433 online                postgres /var/lib/postgresql/14/main /var/log/postgresql/postgresql-14-main.log

This explains how it got into this mess on my system. The default port is 5432, but after I upgraded from version 12 to 14, the server was setup to listen to 5433, presumably because it considered 5432 as already taken. Two alternatives here, get the server to listen on 5432 which is the client’s default, or get the client to use 5433.

Let’s try it by changing the client’s parameters:

$ sudo su postgres -c "psql --port=5433"
psql (14.0 (Ubuntu 14.0-1.pgdg21.04+1))
Type "help" for help.

postgres=#

It worked! Now, to make it permanent I’m supposed to put this setting on a psqlrc or ~/.psqlrc file. The thin documentation on this (under «Files») was not helpful to me as I was not sure on the syntax and my attempts did not change the client’s default, so I moved on.

To change the server I looked for the postgresql.conf mentioned in the documentation but could not find the file. I did however see /var/lib/postgresql/14/main/postgresql.auto.conf so I created it on the same directory with the content:

port = 5432

Restarted the server: sudo systemctl restart postgresql

But the error persisted because, as the logs confirmed, the port did not change:

$ tail /var/log/postgresql/postgresql-14-main.log
...
2021-10-29 16:36:12.195 UTC [25236] LOG:  listening on IPv4 address "127.0.0.1", port 5433
2021-10-29 16:36:12.198 UTC [25236] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5433"
2021-10-29 16:36:12.204 UTC [25237] LOG:  database system was shut down at 2021-10-29 16:36:12 UTC
2021-10-29 16:36:12.210 UTC [25236] LOG:  database system is ready to accept connections

After other attempts did not succeed, I eventually decided to use a workaround: to redirect the client’s requests on 5432 to 5433:

ln -s /var/run/postgresql/.s.PGSQL.5433 /var/run/postgresql/.s.PGSQL.5432

This is what I have now:

$ ls -lah /var/run/postgresql/
total 8.0K
drwxrwsr-x  4 postgres postgres  160 Oct 29 16:40 .
drwxr-xr-x 36 root     root     1.1K Oct 29 14:08 ..
drwxr-s---  2 postgres postgres   40 Oct 29 14:33 12-main.pg_stat_tmp
drwxr-s---  2 postgres postgres  120 Oct 29 16:59 14-main.pg_stat_tmp
-rw-r--r--  1 postgres postgres    6 Oct 29 16:36 14-main.pid
lrwxrwxrwx  1 postgres postgres   33 Oct 29 16:40 .s.PGSQL.5432 -> /var/run/postgresql/.s.PGSQL.5433
srwxrwxrwx  1 postgres postgres    0 Oct 29 16:36 .s.PGSQL.5433
-rw-------  1 postgres postgres   70 Oct 29 16:36 .s.PGSQL.5433.lock

This means I can now just run psql without having to explicitly set the port to 5433. Now, this is a hack and I would not recommend it. But in my development system I am happy with it for now, because I don’t have more time to spend on this. This is why I shared the steps and the links so that you can find a proper solution for your case.

This issue comes from installing the postgres package without a version number. Although postgres will be installed and it will be the correct version, the script to setup the cluster will not run correctly; it’s a packaging issue.

If you’re comfortable with postgres there is a script you can run to create this cluster and get postgres running. However, there’s an easier way.

First purge the old postgres install, which will remove everything of the old installation, including databases, so back up your databases first.. The issue currently lies with 9.1 so I will assume that’s what you have installed

sudo apt-get remove --purge postgresql-9.1

Now simply reinstall

sudo apt-get install postgresql-9.1

Note the package name with the version number. HTH.

Thomas Ward's user avatar

Thomas Ward

71.8k30 gold badges173 silver badges237 bronze badges

answered Aug 19, 2013 at 23:54

Stewart's user avatar

StewartStewart

1,1581 gold badge7 silver badges7 bronze badges

3

The error message refers to a Unix-domain socket, so you need to tweak your netstat invocation to not exclude them. So try it without the option -t:

netstat -nlp | grep 5432

I would guess that the server is actually listening on the socket /tmp/.s.PGSQL.5432 rather than the /var/run/postgresql/.s.PGSQL.5432 that your client is attempting to connect to. This is a typical problem when using hand-compiled or third-party PostgreSQL packages on Debian or Ubuntu, because the source default for the Unix-domain socket directory is /tmp but the Debian packaging changes it to /var/run/postgresql.

Possible workarounds:

  • Use the clients supplied by your third-party package (call /opt/djangostack-1.3-0/postgresql/bin/psql). Possibly uninstall the Ubuntu-supplied packages altogether (might be difficult because of other reverse dependencies).
  • Fix the socket directory of the third-party package to be compatible with Debian/Ubuntu.
  • Use -H localhost to connect via TCP/IP instead.
  • Use -h /tmp or equivalent PGHOST setting to point to the right directory.
  • Don’t use third-party packages.

Nj Subedi's user avatar

answered Jun 27, 2011 at 17:41

Peter Eisentraut's user avatar

3

This works for me:

Edit: postgresql.conf

sudo nano /etc/postgresql/9.3/main/postgresql.conf

Enable or add:

listen_addresses = '*'

Restart the database engine:

sudo service postgresql restart

Also, you can check the file pg_hba.conf

sudo nano /etc/postgresql/9.3/main/pg_hba.conf

And add your network or host address:

host    all             all             192.168.1.0/24          md5

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Oct 9, 2014 at 13:17

angelous's user avatar

angelousangelous

3913 silver badges2 bronze badges

6

You can use psql -U postgres -h localhost to force the connection to happen over TCP instead of UNIX domain sockets; your netstat output shows that the PostgreSQL server is listening on localhost’s port 5432.

You can find out which local UNIX socket is used by the PostgrSQL server by using a different invocavtion of netstat:

netstat -lp --protocol=unix | grep postgres

At any rate, the interfaces on which the PostgreSQL server listens to are configured in postgresql.conf.

answered Jun 26, 2011 at 12:51

Riccardo Murri's user avatar

Riccardo MurriRiccardo Murri

16.3k7 gold badges52 silver badges51 bronze badges

0

Just create a softlink like this :

ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

answered Jul 9, 2012 at 1:35

Uriel's user avatar

UrielUriel

2012 silver badges2 bronze badges

4

I make it work by doing this:

dpkg-reconfigure locales

Choose your preferred locales then run

pg_createcluster 9.5 main --start

(9.5 is my version of postgresql)

/etc/init.d/postgresql start

and then it works!

sudo su - postgres
psql

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Sep 13, 2016 at 9:05

mymusise's user avatar

mymusisemymusise

1911 silver badge2 bronze badges

2

I had to compile PostgreSQL 8.1 on Debian Squeeze because I am using Project Open, which is based on OpenACS and will not run on more recent versions of PostgreSQL.

The default compile configuration puts the unix_socket in /tmp, but Project Open, which relies on PostgreSQL, would not work because it looks for the unix_socket at /var/run/postgresql.

There is a setting in postgresql.conf to set the location of the socket. My problem was that either I could set for /tmp and psql worked, but not project open, or I could set it for /var/run/postgresql and psql would not work but project open did.

One resolution to the issue is to set the socket for /var/run/postgresql and then run psql, based on Peter’s suggestion, as:

psql -h /var/run/postgresql

This runs locally using local permissions. The only drawback is that it is more typing than simply «psql».

The other suggestion that someone made was to create a symbolic link between the two locations. This also worked, but, the link disappeared upon reboot. It maybe easier to just use the -h argument, however, I created the symbolic link from within the PostgreSQL script in /etc/init.d. I placed the symbolic link create command in the «start» section. Of course, when I issue a stop and start or restart command, it will try to recreate an existing symbolic link, but other than warning message, there is probably no harm in that.

In my case, instead of:

ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

I have

ln -s /var/run/postgresql/.s.PGSQL.5432 /tmp/.s.PGSQL.5432

and have explicitly set the unix_socket to /var/run/postgresql/.s.PGSQL.5432 in postgresql.conf.

Peachy's user avatar

Peachy

7,03710 gold badges36 silver badges45 bronze badges

answered Nov 6, 2012 at 3:22

Joe's user avatar

JoeJoe

611 silver badge1 bronze badge

1

If your Postgres service is up and running without any error or there is no error in starting the Postgres service and still you are getting the mentioned error, follow these steps

Step1: Running pg_lsclusters will list all the postgres clusters running on your device

eg:

Ver Cluster Port Status Owner    Data directory               Log file
9.6 main    5432 online postgres /var/lib/postgresql/9.6/main /var/log/postgresql/postgresql-9.6-main.log

most probably the status will be down in your case and postgres service

Step 2: Restart the pg_ctlcluster

#format is pg_ctlcluster <version> <cluster> <action>
sudo pg_ctlcluster 9.6 main start

#restart postgresql service
sudo service postgresql restart

Step 3: Step 2 failed and threw error

If this process is not successful it will throw an error. You can see the error log on /var/log/postgresql/postgresql-9.6-main.log

My error was:

FATAL: could not access private key file "/etc/ssl/private/ssl-cert-snakeoil.key": Permission denied
Try adding `postgres` user to the group `ssl-cert`

Step 4: check ownership of postgres

Make sure that postgres is the owner of /var/lib/postgresql/version_no/main

If not, run

sudo chown postgres -R /var/lib/postgresql/9.6/main/

Step 5: Check postgres user belongs to ssl-cert user group

It turned out that I had erroneously removed the Postgres user from the ssl-cert group. Run the below code to fix the user group issue and fix the permissions

#set user to group back with
sudo gpasswd -a postgres ssl-cert

# Fix ownership and mode
sudo chown root:ssl-cert  /etc/ssl/private/ssl-cert-snakeoil.key
sudo chmod 740 /etc/ssl/private/ssl-cert-snakeoil.key

# now postgresql starts! (and install command doesn't fail anymore)
sudo service postgresql restart

Nwawel A Iroume's user avatar

answered Apr 16, 2018 at 14:44

Noushad's user avatar

NoushadNoushad

1711 silver badge5 bronze badges

1

I found uninstalling Postgres sounds unconvincing.
This helps to solve my problem:

  1. Start the postgres server:

    sudo systemctl start postgresql
    
  2. Make sure that the server starts on boot:

    sudo systemctl enable postgresql
    

Detail information can be found on DigitalOcean site Here.

David Foerster's user avatar

answered Feb 1, 2018 at 15:45

parlad's user avatar

parladparlad

2294 silver badges11 bronze badges

Solution:

Do this

export LC_ALL="en_US.UTF-8"

and this. (9.3 is my current PostgreSQL version. Write your version!)

sudo pg_createcluster 9.3 main --start

answered Feb 23, 2016 at 21:47

bogdanvlviv's user avatar

1

In my case it was caused by a typo I made while editing /etc/postgresql/9.5/main/pg_hba.conf

I changed:

# Database administrative login by Unix domain socket
local   all             postgres                                peer

to:

# Database administrative login by Unix domain socket
local   all             postgres                                MD5

But MD5 had to be lowercase md5:

# Database administrative login by Unix domain socket
local   all             postgres                                md5

answered Nov 29, 2016 at 10:15

Mehdi Nellen's user avatar

1

I failed to solve this problem with my postgres-9.5 server. After 3 days of zero progress trying every permutation of fix on this and other sites I decided to re-install the server and lose 5 days worth of work. But, I did replicate the issue on the new instance. This might provide some perspective on how to fix it before you take the catastrophic approach I did.

First, disable all logging settings in postgresql.conf. This is the section:

# ERROR REPORTING AND LOGGING

Comment out everything in that section. Then restart the service.

When restarting, use /etc/init.d/postgresql start or restart
I found it helpful to be in superuser mode while restarting. I had a x-window open just for that operation. You can establish that superuser mode with sudo -i.

Verify that the server can be reached with this simple command: psql -l -U postgres

If that doesn’t fix it, then consider this:

I was changing the ownership on many folders while trying to find a solution. I knew that I’d probably be trying to revert those folder ownerships and chmods for 2 more days. If you have already messed with those folder ownerships and don’t want to completely purge your server, then start tracking the settings for all impacted folders to bring them back to the original state. You might want to try to do a parallel install on another system and systematically check the ownership and settings of all folders. Tedious, but you may be able to get access to your data.

Once you do gain access, systematically change each relevant line in the # ERROR REPORTING AND LOGGING section of the postgresql.conf file. Restart and test. I found that the default folder for the logs was causing a failure. I specifically commented out log_directory. The default folder the system drops the logs into is then /var/log/postgresql.

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Jan 19, 2017 at 1:34

jurban1997's user avatar

Possibly it could have happened because you changed the permissions of the /var/lib/postgresql/9.3/main folder.

Try changing it to 700 using the command below:

sudo chmod 700 main

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Nov 6, 2014 at 13:01

Farzin's user avatar

This is not exactly related to the question since I’m using Flask, but this was the exact error I was getting and this was the most relevant thread to get ideas.

My setup: Windows Subsystem for Linux, Docker-compose w/ makefile w/ dockerfile, Flask, Postgresql (using a schema consisting of tables)

To connect to postgres, setup your connection string like this:

from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://<user>:<password>@<container_name_in_docker-compose.yml>/<database_name>"

NOTE: I never got any IP (e.g. localhost, 127.0.0.1) to work using any method in this thread. Idea for using the container name instead of localhost came from here: https://github.com/docker-library/postgres/issues/297

Set your schema:

from sqlalchemy import MetaData
db = SQLAlchemy(app, metadata=MetaData(schema="<schema_name>"))

Set your search path for your functions when you setup your session:

db.session.execute("SET search_path TO <schema_name>")

answered Mar 29, 2019 at 21:30

Josh Graham's user avatar

The most upvoted answer isn’t even remotely correct because you can see in the question the server is running on the expected port (he shows this with netstat).

While the OP did not mark the other answer as chosen, they commented that the other answer (which makes sense and works) was sufficient,

But for these reasons that solution is poor and insecure even if it the server wasn’t running on port 5432:


What you’re doing here when you say --purge is you’re deleting the configuration file for PostgreSQL ((as well as all of the data with the database. You or may not even see a warning about this, but here is the warning just to show you now,

Removing the PostgreSQL server package will leave existing database clusters intact, i.e. their configuration, data, and log directories will not be removed. On purging the package, the directories can optionally be removed. Remove PostgreSQL directories when package is purged? [prompt for yes or no]

When you add it again PostgreSQL is reinstalling it to a port number that’s not taken (which may be the port number you expect). Before you even try this solution, you need to answer a few questions along the same line:

  • Do I want multiple versions of PostgreSQL on my machine?
  • Do I want an older version of PostgreSQL?
  • What do I want to happen when I dist-upgrade and there is a newer version?

Currently when you dist-upgrade on Ubuntu (and any Debian variant), the new version of PostgreSQL is installed alongside the old copy and the port number on the new copy is the port number of the old copy + 1. So you can just start it up, increment the port number in your client and you’ve got a new install! And you have the old install to fall back on — it’s safe!

However, if you only one want version of PostgreSQL purging to change the configuration is still not the right option because it will destroy your database. The only time this could even be acceptable is you want to destroy everything related to PostgreSQL. You’re better off ensuring your database is correct and then merely editing the configuration file so the new install runs on the old port number

#!/bin/bash

# We can find the version number of the newest PostgreSQL with this
VERSION=$(dpkg-query -W -f "${Version}" 'postgresql' | sed -e's/+.*//')
PGCONF="/etc/postgresql/${VERSION}/main/postgresql.conf"

# Then we can update the port.
sudo sed -ie '/port = /s/.*/port = 5432/' "$PGCONF"

sudo systemctl restart postgresql

Do not install a specific version of PostgreSQL. Only ever install postgresql. If you install a specific version then when you dist-upgrade your version will simply remain on your computer forever without upgrades. The repo will no longer have the security patches for the old version (which they don’t support). This must always be suboptimal to getting a newer version that they do support, running on a different port number.

answered Aug 4, 2021 at 18:30

Evan Carroll's user avatar

Evan CarrollEvan Carroll

7,30615 gold badges53 silver badges87 bronze badges

I had the exact same problem Peter Eisentraut described. Using the netstat -nlp | grep 5432 command, I could see the server was listening on socket /tmp/.s.PGSQL.5432.

To fix this, just edit your postgresql.conf file and change the following lines:

listen_addresses = '*'
unix_socket_directories = '/var/run/postgresql'

Now run service postgresql-9.4 restart (Replace 9-4 with your version), and remote connections should be working now.

Now to allow local connections, simply create a symbolic link to the /var/run/postgresql directory.

ln -s /var/run/postgresql/.s.PGSQL.5432 /tmp/.s.PGSQL.5432

Don’t forget to make sure your pg_hba.conf is correctly configured too.

answered Nov 20, 2015 at 16:44

Justin's user avatar

In my case, all i had to do was this:

sudo service postgresql restart

and then

sudo -u postgres psql

This worked just fine.
Hope it helps.
Cheers :) .

answered Jun 29, 2017 at 17:21

Pranay Dugar's user avatar

Find your file:

sudo find /tmp/ -name .s.PGSQL.5432

Result:

/tmp/.s.PGSQL.5432

Login as postgres user:

su postgres
psql -h /tmp/ yourdatabase

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Jan 30, 2017 at 15:18

Waldeyr Mendes da Silva's user avatar

I had the same problem (on Ubuntu 15.10 (wily)). sudo find / -name 'pg_hba.conf' -print or sudo find / -name 'postgresql.conf' -print turned up empty. Before that it seemed that multiple instances of postgresql were installed.

You might have similar when you see as installed, or dependency problems listing

.../postgresql
.../postgresql-9.x 

and so on.

In that case you must sudo apt-get autoremove each package 1 by 1.

Then following this to the letter and you will be fine. Especially when it comes to key importing and adding to source list FIRST

sudo apt-get update && sudo apt-get -y install python-software-properties && wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

If not using wily, replace wily with your release, i.e with the output of lsb_release -cs

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ wily-pgdg main" >> /etc/apt/sources.list.d/postgresql.list'
sudo apt-get update && sudo apt-get install postgresql-9.3 pgadmin3

And then you should be fine and be able to connect and create users.

Expected output:

Creating new cluster 9.3/main ...
config /etc/postgresql/9.3/main
data   /var/lib/postgresql/9.3/main
locale en_US.UTF-8
socket /var/run/postgresql
port   5432

Source of my solutions (credits)

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Feb 5, 2016 at 16:43

Grmn's user avatar

While having the same issue I tried something different:

Starting the postgresql daemon manually I got:

FATAL:  could not create shared memory segment ...
   To reduce the request size (currently 57237504 bytes), reduce PostgreSQL's
   shared memory usage, perhaps by reducing shared_buffers or max_connections.

So what I did was to set a lower limit for shared_buffers and max_connections into postgresql.conf and restart the service.

This fixed the problem!

Here’s the full error log:

$ sudo service postgresql start
 * Starting PostgreSQL 9.1 database server                                                                                                                                                               * The PostgreSQL server failed to start. Please check the log output:
2013-06-26 15:05:11 CEST FATAL:  could not create shared memory segment: Invalid argument
2013-06-26 15:05:11 CEST DETAIL:  Failed system call was shmget(key=5432001, size=57237504, 03600).
2013-06-26 15:05:11 CEST HINT:  This error usually means that PostgreSQL's request for a shared memory segment exceeded your kernel's SHMMAX parameter.  You can either reduce the request size or reconfigure the kernel with larger SHMMAX.  To reduce the request size (currently 57237504 bytes), reduce PostgreSQL's shared memory usage, perhaps by reducing shared_buffers or max_connections.
    If the request size is already small, it's possible that it is less than your kernel's SHMMIN parameter, in which case raising the request size or reconfiguring SHMMIN is called for.
    The PostgreSQL documentation contains more information about shared memory configuration.

Zanna's user avatar

Zanna

68.9k56 gold badges215 silver badges327 bronze badges

answered Jun 26, 2013 at 13:29

DrFalk3n's user avatar

After many exhausting attempts, I found the solution based on other posts!

dpkg -l | grep postgres
apt-get --purge remove <package-founded-1> <package-founded-2>
whereis postgres
whereis postgresql
sudo rm -rf <paths-founded>
sudo userdel -f postgres

Kevin Bowen's user avatar

Kevin Bowen

19.3k55 gold badges76 silver badges81 bronze badges

answered Apr 22, 2019 at 23:46

Douglas Rosa's user avatar

1

  1. Check the status of postgresql:

    service postgresql status
    

    If it shows online, proceed to step no 3 else execute step no 2.

  2. To make postgresql online, execute the following command:

    sudo service postgresql start
    

    Now check the status by running the command of the previous step. It should show online.

  3. To start psql session, execute the following command:

    sudo su postreg
    
  4. Finally, check if it’s working or not by executing:

    psql
    

BeastOfCaerbannog's user avatar

answered May 29, 2021 at 12:21

iAmSauravSharan's user avatar

Restart postgresql by using the command

sudo /opt/bitnami/ctlscript.sh restart postgresql

enter image description here

answered Apr 26, 2022 at 9:41

Jasir's user avatar

This error could mean a lot of different things.

In my case, I was running PostgreSQL 12 on a virtual machine.

I had changed the shared_buffer config and apparently, the system administrator edited the memory config for the virtual machine reducing the RAM allocation from where it was to below what I had set for the shared_buffer.

I figured that out by looking at the log in

/var/log/postgresql/postgresql-12-main.log

and after that I restarted the service using

sudo systemctl restart postgresql.service

that’s how it worked

answered Jun 30, 2022 at 9:47

mekbib.awoke's user avatar

Create postgresql directory inside run and then run the following command.

ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

answered Apr 26, 2019 at 5:35

Pradeep Maurya's user avatar

1

Simply add /tmp unix_socket_directories

postgresql.conf

unix_socket_directories = '/var/run/postgresql,/tmp'

answered Jun 17, 2019 at 1:00

BlueNC's user avatar

2

I had this problem with another port. The problem was, that I had a system variable in /etc/environments with the following value:

PGPORT=54420

As I removed it (and restarted), psql was able to connect.

answered Jul 18, 2021 at 14:46

Bevor's user avatar

BevorBevor

4908 silver badges18 bronze badges

2

Сейчас столкнулся с тем же самым и стал гуглить, нашел этот вопрос. Потом вспомнил, что часом ранее редактировал файл start.conf, который находится в /etc/postgresql/дальше сами найдете)
В общем, я хотел, чтобы постгрес не запускался при старте машины, чтобы я мог запускать его через сервис пострес старт и поменял в том файле auto на manual, перезагрузил, смотрю — пострес не запустился, отлично. Но потом случился сабж. Потом поменял обратно на авто, опять перезагрузка, и проблема решилась. Возможно, кроме запуска сервиса нужно еще что-то запустить, чтобы все хорошо работало, этого уж я не знаю, не лютый линуксоид)

Обновление 17.07.2019
После перезагрузки компа столкнулся с тем же самым. Залез в логи, там прямым текстом написано

2019-07-17 15:12:07.950 MSK [547] ВАЖНО: для каталога данных «/var/lib/postgresql/11/main» установлены неправильные права доступа
2019-07-17 15:12:07.950 MSK [547] ПОДРОБНОСТИ: Маска прав должна быть u=rwx (0700) или u=rwx,g=rx (0750).
pg_ctl: не удалось запустить сервер
Изучите протокол выполнения.

Зачмодил каталог, и все заработало.

Я установил стек Bitnami Django, который включал PostgreSQL 8.4.

Когда я бегу psql -U postgres Я получаю следующую ошибку:

psql: 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"?

PG определенно работает и pg_hba.conf файл выглядит так:

# TYPE  DATABASE        USER            CIDR-ADDRESS            METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

Что дает?

«Доказательство», что pg работает:

[email protected]:/home/assaf# ps axf | grep postgres
14338 ?        S      0:00 /opt/djangostack-1.3-0/postgresql/bin/postgres -D /opt/djangostack-1.3-0/postgresql/data -p 5432
14347 ?        Ss     0:00  _ postgres: writer process                                                                        
14348 ?        Ss     0:00  _ postgres: wal writer process                                                                    
14349 ?        Ss     0:00  _ postgres: autovacuum launcher process                                                           
14350 ?        Ss     0:00  _ postgres: stats collector process                                                               
15139 pts/1    S+     0:00              _ grep --color=auto postgres
[email protected]:/home/assaf# netstat -nltp | grep 5432
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      14338/postgres  
tcp6       0      0 ::1:5432                :::*                    LISTEN      14338/postgres  
[email protected]:/home/assaf# 

2011-06-26 12:21

28
ответов

Эта проблема возникает из-за установки postgres пакет без номера версии. Хотя postgres будет установлена ​​и будет правильной версией, скрипт для настройки кластера будет работать некорректно; это проблема упаковки.

Если вам удобно postgres есть скрипт, который вы можете запустить, чтобы создать этот кластер и получить postgres Бег. Тем не менее, есть более простой способ.

Сначала удалите старую установку postgres. В настоящее время проблема заключается в 9.1, поэтому я буду считать, что это то, что вы установили

sudo apt-get remove --purge postgresql-9.1

Теперь просто переустановите

sudo apt-get install postgresql-9.1

Запишите название пакета с номером версии. НТН.


Stewart

19 авг ’13 в 23:54
2013-08-19 23:54

2013-08-19 23:54

The error message refers to a Unix-domain socket, so you need to tweak your netstat invocation to not exclude them. So try it without the option -t:

netstat -nlp | grep 5432

I would guess that the server is actually listening on the socket /tmp/.s.PGSQL.5432 rather than the /var/run/postgresql/.s.PGSQL.5432 that your client is attempting to connect to. This is a typical problem when using hand-compiled or third-party PostgreSQL packages on Debian or Ubuntu, because the source default for the Unix-domain socket directory is /tmp but the Debian packaging changes it to /var/run/postgresql,

Возможные обходные пути:

  • Use the clients supplied by your third-party package (call /opt/djangostack-1.3-0/postgresql/bin/psql). Возможно, удалите все пакеты, поставляемые с Ubuntu (это может быть сложно из-за других обратных зависимостей).
  • Исправьте каталог сокетов стороннего пакета, чтобы он был совместим с Debian/Ubuntu.
  • использование -H localhost to connect via TCP/IP instead.
  • использование -h /tmp or equivalent PGHOST setting to point to the right directory.
  • Не используйте сторонние пакеты.

2011-06-27 17:41

Это работает для меня:

Изменить: postgresql.conf

sudo nano /etc/postgresql/9.3/main/postgresql.conf

Включить или добавить:

listen_addresses = '*'

Перезапустите ядро ​​базы данных:

sudo service postgresql restart

Также вы можете проверить файл pg_hba.conf

sudo nano /etc/postgresql/9.3/main/pg_hba.conf

И добавьте адрес своей сети или хоста:

host    all             all             192.168.1.0/24          md5


angelous

09 окт ’14 в 13:17
2014-10-09 13:17

2014-10-09 13:17

Ты можешь использовать psql -U postgres -h localhost заставить соединение происходить через TCP вместо доменных сокетов UNIX; ваш netstat вывод показывает, что сервер PostgreSQL прослушивает порт 5432 локального хоста.

Вы можете узнать, какой локальный сокет UNIX используется сервером PostgrSQL, используя другой вызов netstat:

netstat -lp --protocol=unix | grep postgres

В любом случае, интерфейсы, на которых слушает сервер PostgreSQL, настроены в postgresql.conf,

2011-06-26 12:51

Просто создайте мягкую ссылку, подобную этой:

ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432


Uriel

09 июл ’12 в 01:35
2012-07-09 01:35

2012-07-09 01:35

Я заставляю это работать этим:

dpkg-reconfigure locales

Выберите предпочитаемые локали и запустите

pg_createcluster 9.5 main --start

(9.5 — это моя версия postgresql)

/etc/init.d/postgresql start

и тогда это работает!

sudo su - postgres
psql


mymusise

13 сен ’16 в 09:05
2016-09-13 09:05

2016-09-13 09:05

Если ваша служба Postgres запущена и работает без каких-либо ошибок или при запуске службы Postgres нет ошибок, но вы все еще получаете указанную ошибку, выполните следующие действия.

Шаг 1: Бег pg_lsclusters выведет список всех кластеров postgres, работающих на вашем устройстве

например:

Ver Cluster Port Status Owner    Data directory               Log file
9.6 main    5432 online postgres /var/lib/postgresql/9.6/main /var/log/postgresql/postgresql-9.6-main.log

Скорее всего, статус будет ниже в вашем случае и сервис Postgres

Шаг 2: перезапустите pg_ctlcluster

#format is pg_ctlcluster <version> <cluster> <action>
sudo pg_ctlcluster 9.6 main start

#restart postgres
sudo service postgres restart

Шаг 3: Шаг 2 не удался и выдал ошибку

Если этот процесс не будет успешным, он выдаст ошибку. Вы можете увидеть журнал ошибок на /var/log/postgresql/postgresql-9.6-main.log

Моя ошибка была:

FATAL: could not access private key file "/etc/ssl/private/ssl-cert-snakeoil.key": Permission denied
Try adding `postgres` user to the group `ssl-cert`

Шаг 4: проверьте право собственности на postgres

Удостоверься что postgres является владельцем /var/lib/postgresql/version_no/main

Если нет, запустите

sudo chown postgres -R /var/lib/postgresql/9.6/main/

Шаг 5: Проверьте, что пользователь postgres принадлежит к группе пользователей ssl-cert

Оказалось, что я ошибочно удалил пользователя Postgres из ssl-cert группа. Запустите приведенный ниже код, чтобы исправить проблему группы пользователей и исправить разрешения

#set user to group back with
sudo gpasswd -a postgres ssl-cert

# Fix ownership and mode
sudo chown root:ssl-cert  /etc/ssl/private/ssl-cert-snakeoil.key
sudo chmod 740 /etc/ssl/private/ssl-cert-snakeoil.key

# now postgresql starts! (and install command doesn't fail anymore)
sudo service postgres restart


Noushad

16 апр ’18 в 14:44
2018-04-16 14:44

2018-04-16 14:44

Мне пришлось скомпилировать PostgreSQL 8.1 на Debian Squeeze, потому что я использую Project Open, который основан на OpenACS и не будет работать на более поздних версиях PostgreSQL.

Конфигурация компиляции по умолчанию помещает unix_socket в /tmp, но Project Open, который опирается на PostgreSQL, не будет работать, потому что он ищет unix_socket в /var/run/postgresql,

Есть настройка в postgresql.conf установить местоположение розетки. Моя проблема заключалась в том, что либо я мог установить для /tmp а также psql работал, но проект не открыт, или я мог бы установить его для /var/run/postgresql а также psql не будет работать, но проект открыт.

Одним из решений этой проблемы является установка сокета для /var/run/postgresql а потом беги psqlпо предложению Петра, как:

psql -h /var/run/postgresql

Это выполняется локально с использованием локальных разрешений. Единственным недостатком является то, что он больше печатает, чем просто «psql».

Другое предложение, которое сделал кто-то, состояло в том, чтобы создать символическую связь между двумя местоположениями. Это также сработало, но ссылка исчезла после перезагрузки. Возможно, проще использовать аргумент -h, однако я создал символическую ссылку из скрипта PostgreSQL в /etc/init.d, Я разместил символическую команду создания ссылки в разделе «Пуск». Конечно, когда я запускаю команду остановки и запуска или перезапуска, она будет пытаться воссоздать существующую символическую ссылку, но, кроме предупреждающего сообщения, в этом нет никакого вреда.

В моем случае вместо:

ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

я имею

ln -s /var/run/postgresql/.s.PGSQL.5432 /tmp/.s.PGSQL.5432

и явно установить unix_socket в /var/run/postgresql/.s.PGSQL.5432 в postgresql.conf,


Joe

06 ноя ’12 в 03:22
2012-11-06 03:22

2012-11-06 03:22

Я обнаружил, что удаление Postgres звучит неубедительно. Это помогает решить мою проблему:

  1. Запустите сервер postgres:

    sudo systemctl start postgresql
    
  2. Убедитесь, что сервер запускается при загрузке:

    sudo systemctl enable postgresql
    

Подробную информацию можно найти на сайте DigitalOcean здесь.

2018-02-01 15:45

Решение:

Сделай это

export LC_ALL="en_US.UTF-8"

и это. (9.3 — это моя текущая версия PostgreSQL. Напишите свою версию!)

sudo pg_createcluster 9.3 main --start

2016-02-23 21:47

В моем случае это было вызвано опечаткой, которую я сделал при редактировании /etc/postgresql/9.5/main/pg_hba.conf

Я изменился:

# Database administrative login by Unix domain socket
local   all             postgres                                peer

чтобы:

# Database administrative login by Unix domain socket
local   all             postgres                                MD5

Но MD5 должен был быть в нижнем регистре md5:

# Database administrative login by Unix domain socket
local   all             postgres                                md5

2016-11-29 10:15

Я не смог решить эту проблему с моим сервером postgres-9.5. После 3 дней нулевого прогресса, пробуя каждую перестановку исправлений на этом и других сайтах, я решил переустановить сервер и потерять 5 дней работы. Но я повторил проблему на новом экземпляре. Это может дать некоторое представление о том, как это исправить, прежде чем использовать катастрофический подход, который я сделал.

Во-первых, отключите все параметры ведения журнала в postgresql.conf. Это раздел:

# ERROR REPORTING AND LOGGING

Закомментируйте все в этом разделе. Затем перезапустите сервис.

При перезапуске используйте /etc/init.d/postgresql start или же restartЯ нашел полезным находиться в режиме суперпользователя при перезапуске. У меня было открыто окно x только для этой операции. Вы можете установить этот режим суперпользователя с помощью sudo -i,

Убедитесь, что к серверу можно подключиться с помощью этой простой команды: psql -l -U postgres

Если это не помогает, то подумайте:

Я менял владельца многих папок, пытаясь найти решение. Я знал, что я, вероятно, буду пытаться вернуть владельцы этих папок и chmodеще 2 дня. Если вы уже перепутали владельцев этих папок и не хотите полностью очищать свой сервер, начните отслеживать настройки всех затронутых папок, чтобы вернуть их в исходное состояние. Возможно, вы захотите попробовать выполнить параллельную установку в другой системе и систематически проверять владение и настройки всех папок. Утомительно, но вы можете получить доступ к своим данным.

Получив доступ, систематически меняйте каждую соответствующую строку в # ERROR REPORTING AND LOGGING раздел postgresql.conf файл. Перезапустите и проверьте. Я обнаружил, что папка по умолчанию для журналов вызывает сбой. Я специально закомментировал log_directory, Папка по умолчанию, в которую система сбрасывает журналы, /var/log/postgresql,

2017-01-19 01:34

Ответ , получивший наибольшее количество голосов , даже отдаленно неверен, потому что вы можете видеть в вопросе, что сервер работает на ожидаемом порту (он показывает это с помощью netstat).

Хотя ОП не отметил другой ответ как выбранный, они отметили, что другого ответа (который имеет смысл и работает) было достаточно ,

Но по этим причинам это решение плохое и небезопасное , даже если сервер не работает на порту 5432:


Что ты здесь делаешь, когда говоришь
--purgeвы удаляете файл конфигурации для PostgreSQL ((а также все данные с базой данных. Возможно, вы даже не видите предупреждение об этом, но это предупреждение просто для того, чтобы показать вам сейчас,

Удаление пакета сервера PostgreSQL оставит существующие кластеры баз данных нетронутыми, т. е. их каталоги конфигурации, данных и журналов не будут удалены. При очистке пакета каталоги могут быть удалены. Удалить каталоги PostgreSQL при очистке пакета? [подскажите да или нет]

Когда вы добавляете его снова, PostgreSQL переустанавливает его на номер порта, который не занят (который может быть тем номером порта, который вы ожидаете). Прежде чем вы даже попробуете это решение , вам нужно ответить на несколько вопросов в том же духе:

  • Нужно ли мне несколько версий PostgreSQL на моей машине?
  • Нужна ли мне более старая версия PostgreSQL?
  • Что я хочу, чтобы произошло, когда я и есть более новая версия?

В настоящее время, когда вы используете Ubuntu (и любой вариант Debian), новая версия PostgreSQL устанавливается вместе со старой копией, а номер порта в новой копии равен номеру порта старой копии + 1. Таким образом, вы можете просто запустить его, увеличьте номер порта в вашем клиенте, и вы получите новую установку! И у вас есть старая установка, на которую можно вернуться — это безопасно!

Однако, если вам нужна только одна версия очистки PostgreSQL для изменения конфигурации, это все равно не лучший вариант, поскольку он уничтожит вашу базу данных . Единственный случай, когда это может быть допустимо, — это когда вы хотите уничтожить все , что связано с PostgreSQL. Вам лучше убедиться, что ваша база данных верна, а затем просто отредактировать файл конфигурации, чтобы новая установка выполнялась на старом номере порта.

      #!/bin/bash

# We can find the version number of the newest PostgreSQL with this
VERSION=$(dpkg-query -W -f "${Version}" 'postgresql' | sed -e's/+.*//')
PGCONF="/etc/postgresql/${VERSION}/main/postgresql.conf"

# Then we can update the port.
sudo sed -ie '/port = /s/.*/port = 5432/' "$PGCONF"

sudo systemctl restart postgresql

Не устанавливайте определенную версию PostgreSQL. Всегда устанавливайте только
postgresql
. Если вы устанавливаете конкретную версию, то при
dist-upgradeваша версия просто останется на вашем компьютере навсегда без обновлений. В репозитории больше не будет исправлений безопасности для старой версии (которую они не поддерживают). Это всегда должно быть неоптимально для получения более новой версии, которую они поддерживают, работающей на другом номере порта.

2021-08-04 18:30

Возможно, это могло произойти, потому что вы изменили права доступа /var/lib/postgresql/9.3/main папка.

Попробуйте изменить его на 700, используя команду ниже:

sudo chmod 700 main


Farzin

06 ноя ’14 в 13:01
2014-11-06 13:01

2014-11-06 13:01

Это не совсем связано с вопросом, так как я использую Flask, но это была именно та ошибка, которую я получил, и это была самая важная тема для получения идей.

Моя установка: подсистема Windows для Linux, Docker-compose с make-файлом с dockerfile, Flask, Postgresql (с использованием схемы, состоящей из таблиц)

Чтобы подключиться к postgres, настройте строку подключения следующим образом:

from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://<user>:<password>@<container_name_in_docker-compose.yml>/<database_name>"

ПРИМЕЧАНИЕ. У меня никогда не было IP-адреса (например, localhost, 127.0.0.1) для работы с использованием какого-либо метода в этой теме. Идея использования имени контейнера вместо localhost пришла отсюда: https://github.com/docker-library/postgres/issues/297

Установите вашу схему:

from sqlalchemy import MetaData
db = SQLAlchemy(app, metadata=MetaData(schema="<schema_name>"))

Задайте путь поиска для своих функций при настройке сеанса:

db.session.execute("SET search_path TO <schema_name>")

2019-03-29 21:30

У меня была та же самая проблема, которую описал Питер Эйзентро. С использованием netstat -nlp | grep 5432 команда, я мог видеть, что сервер слушал на сокете /tmp/.s.PGSQL.5432,

Чтобы это исправить, просто отредактируйте postgresql.conf файл и измените следующие строки:

listen_addresses = '*'
unix_socket_directories = '/var/run/postgresql'

Теперь беги service postgresql-9.4 restart (Замените 9-4 вашей версией), и удаленные соединения должны работать сейчас.

Теперь, чтобы разрешить локальные подключения, просто создайте символическую ссылку на /var/run/postgresql каталог.

ln -s /var/run/postgresql/.s.PGSQL.5432 /tmp/.s.PGSQL.5432

Не забудьте убедиться, что ваш pg_hba.conf тоже правильно настроен.

2015-11-20 16:44

У меня была такая же проблема (на Ubuntu 15.10 (хитрый)). sudo find / -name 'pg_hba.conf' -print или же sudo find / -name 'postgresql.conf' -print оказалось пустым. До этого казалось, что было установлено несколько экземпляров postgresql.

Вы можете иметь подобное, когда вы видите, как установлено, или список проблем с зависимостями

.../postgresql
.../postgresql-9.x 

и так далее.

В этом случае вы должны sudo apt-get autoremove каждый пакет 1 на 1.

Тогда следуйте этому письму и у вас все будет хорошо. Особенно когда речь идет об импорте ключей и добавлении их в список источников.

sudo apt-get update && sudo apt-get -y install python-software-properties && wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

Если вы не используете хитрый, замените wily с вашим выпуском, то есть с выводом lsb_release -cs

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ wily-pgdg main" >> /etc/apt/sources.list.d/postgresql.list'
sudo apt-get update && sudo apt-get install postgresql-9.3 pgadmin3

И тогда вы должны быть в порядке и иметь возможность подключаться и создавать пользователей.

Ожидаемый результат:

Creating new cluster 9.3/main ...
config /etc/postgresql/9.3/main
data   /var/lib/postgresql/9.3/main
locale en_US.UTF-8
socket /var/run/postgresql
port   5432

Источник моих решений (кредиты)


Grmn

05 фев ’16 в 16:43
2016-02-05 16:43

2016-02-05 16:43

Эта ошибка может означать много разных вещей.

В моем случае я бежал
PostgreSQL 12на виртуальной машине.

Я изменил конфигурацию, и, по-видимому, системный администратор отредактировал конфигурацию памяти для виртуальной машины, уменьшив выделение ОЗУ с того места, где оно было, до уровня ниже того, что я установил для виртуальной машины.
shared_buffer.

Я понял это, посмотрев логин

      /var/log/postgresql/postgresql-12-main.log

и после этого я перезапустил службу, используя

      sudo systemctl restart postgresql.service

вот как это сработало

2022-06-30 09:47

После многих изнурительных попыток я нашел решение, основанное на других постах!

dpkg -l | grep postgres
apt-get --purge remove <package-founded-1> <package-founded-2>
whereis postgres
whereis postgresql
sudo rm -rf <paths-founded>
sudo userdel -f postgres

2019-04-22 23:46

Имея ту же проблему, я попробовал что-то другое:

Запустив демон postgresql вручную, я получил:

FATAL:  could not create shared memory segment ...
   To reduce the request size (currently 57237504 bytes), reduce PostgreSQL's
   shared memory usage, perhaps by reducing shared_buffers or max_connections.

Так что я сделал, чтобы установить нижний предел для shared_buffers а также max_connections в postgresql.conf а также restart сервис.

Это решило проблему!

Вот полный журнал ошибок:

$ sudo service postgresql start
 * Starting PostgreSQL 9.1 database server                                                                                                                                                               * The PostgreSQL server failed to start. Please check the log output:
2013-06-26 15:05:11 CEST FATAL:  could not create shared memory segment: Invalid argument
2013-06-26 15:05:11 CEST DETAIL:  Failed system call was shmget(key=5432001, size=57237504, 03600).
2013-06-26 15:05:11 CEST HINT:  This error usually means that PostgreSQL's request for a shared memory segment exceeded your kernel's SHMMAX parameter.  You can either reduce the request size or reconfigure the kernel with larger SHMMAX.  To reduce the request size (currently 57237504 bytes), reduce PostgreSQL's shared memory usage, perhaps by reducing shared_buffers or max_connections.
    If the request size is already small, it's possible that it is less than your kernel's SHMMIN parameter, in which case raising the request size or reconfiguring SHMMIN is called for.
    The PostgreSQL documentation contains more information about shared memory configuration.


DrFalk3n

26 июн ’13 в 13:29
2013-06-26 13:29

2013-06-26 13:29

Перезапустите postgresql с помощью команды

      sudo /opt/bitnami/ctlscript.sh restart postgresql


Jasir

26 апр ’22 в 09:41
2022-04-26 09:41

2022-04-26 09:41

  1. Проверьте статус:

            service postgresql status
    

    Если он отображается онлайн, перейдите к шагу № 3, в противном случае выполните шаг № 2.

  2. Делать
    postgresqlонлайн, выполните следующую команду:

            sudo service postgresql start
    

    Теперь проверьте статус, выполнив команду предыдущего шага. Он должен показывать онлайн.

  3. Начать
    psqlсессии выполните следующую команду:

            sudo su postreg
    
  4. Наконец, проверьте, работает ли он или нет, выполнив:

            psql
    

2021-05-29 12:21

В моем случае все, что мне нужно было сделать, это:

sudo service postgresql restart

а потом

sudo -u postgres psql

Это работало просто отлично. Надеюсь, поможет. Ура:) .

2017-06-29 17:21

В моем случае у меня были установлены предыдущие версии, и это вызвало беспорядок. Я очистил эти файлы, удалил все и переустановил Postgres. Это решено.



18 окт ’20 в 19:56
2020-10-18 19:56

2020-10-18 19:56

Найдите свой файл:

sudo find /tmp/ -name .s.PGSQL.5432

Результат:

/tmp/.s.PGSQL.5432

Войти как пользователь postgres:

su postgres
psql -h /tmp/ yourdatabase

2017-01-30 15:18

Создайте каталог postgresql внутри run и затем выполните следующую команду.

ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

2019-04-26 05:35

У меня была эта проблема с другим портом. Проблема была в том, что у меня была системная переменная в
/etc/environmentsсо следующим значением:

PGPORT=54420

Когда я удалил его (и перезапустил), psql смог подключиться.


Bevor

18 июл ’21 в 14:46
2021-07-18 14:46

2021-07-18 14:46

Просто добавьте /tmp unix_socket_directories

postgresql.conf

unix_socket_directories = '/var/run/postgresql,/tmp'


Blue

17 июн ’19 в 04:00
2019-06-17 04:00

2019-06-17 04:00

15.11.2022

567 Просмотры

Psql: Error: Connection To Server On Socket “/Tmp/.S.Pgsql.5432” F With Code Examples

In this tutorial, we will try to find the solution to Psql: Error: Connection To Server On Socket “/Tmp/.S.Pgsql.5432” F through programming. The following code illustrates this.

sudo find /tmp/ -name .s.PGSQL.5432

/tmp//.s.PGSQL.5432

psql -h /tmp/ [dbname]

The solution to the same problem, Psql: Error: Connection To Server On Socket “/Tmp/.S.Pgsql.5432” F, can also be found in a different method, which will be discussed further down with some code examples.

rm /opt/homebrew/var/postgres/postmaster.pid
brew services restart postgresql

Using many examples, we’ve learned how to tackle the Psql: Error: Connection To Server On Socket “/Tmp/.S.Pgsql.5432” F problem.

How do I connect to a PostgreSQL database?

Connect to a PostgreSQL Database Server

  • Step1: Launch the pgAdmin application.
  • Step2: Create a server.
  • Step3: Provide the server name.
  • Step4: Provide the host and password.
  • Step5: Expanding the server.
  • Step6: Open the Query tool.
  • Step7: Enter the command in the Query editor.
  • Step1: Open the psql.

Is Postgres running on port 5432?

The PostgreSQL database service is available on localhost and the default PostgreSQL port is 5432 . A default user ( hosting-db ) and database ( postgres ) exist so you can quickly test your connection and perform management tasks.

The Problem

When connecting to Postgres you might see this error: psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket <some socket>. This happens most often when Postgres’ server daemon process is not running.

The Solution

To troubleshoot this issue, first check to make sure that Postgres is running on the machine you expect it to run. You can use the ps aux command to make sure that the postgres process is currently running. If it’s not, you will need to start Postgres.

Загрузка…

Issue

When I try to open psql with this command:

psql -U postgres

I get this error:

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  Peer authentication failed for user "postgres"

But it connects successfully when I use:

sudo -u postgres psql

Can someone please explain what is happening and how to diagnose/fix this problem? My pg_hba.conf contains the following:


# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer

Solution

Peer authentication means that the connection is only allowed if the name of the database user is the same as the name of the operating system user.

So if you run psql -U postgres as operating system user root or jimmy, it won’t work.

You can specify a mapping between operating system users and database users in pg_ident.conf.

Answered By — Laurenz Albe

Answer Checked By — Mary Flores (WPSolving Volunteer)

Понравилась статья? Поделить с друзьями:
  • Psql ошибка важно роль user не существует
  • Psql ошибка важно роль root не существует
  • Psql игнорировать ошибки
  • Psp ошибка удаления игры
  • Pubg ошибка не удалось выполнить инициализацию steam