1

I'm trying to connect to PostgreSQL Unix domain socket from a python web application with mod_wsgi. Relevant system components:

  • CentOS 7 x64
  • Python 2.7.5
  • SELinux disabled

PostgreSQL is listening on standard port 5432 and I have no problems to use it via TCP/IP at 127.0.0.1:5432, but when I try to connect to its Unix domain socket, I have a following error:

Cannot connect to database:  could not connect to server: No such file or directory
     Is the server running locally and accepting
     connections on Unix domain socket "/tmp/.s.PGSQL.5432"?*

File /tmp/.s.PGSQL.5432 exists and I can connect using psql.

However, when I stop apache with systemctl stop httpd.service and restart it again with /usr/sbin/httpd -DFOREGROUND, everything works fine, including the pages that do require database access

With SELinux disabled, I do not understand why there is problems when httpd start with systemctl start httpd.service.

EDIT:

I've changed unix_socket_directories = '/tmp,/var/pgsql_sock' in /var/lib/pgsql/9.3/data/postgresql.conf. I also changed config in setting.py in my django app HOST='/var/pgsql_sock'. Now it works fine with httpd.service.

tpml7
  • 479
  • 1
  • 5
  • 21
xav
  • 21
  • 5
  • It's a `unix_socket_directories` mismatch between the default compiled into the `libpq` on your `LD_LIBRARY_PATH` or `/etc/ld.so.conf` and the default in the PostgreSQL server you're running. `SHOW unix_socket_directories;` in PostgreSQL will likely output a different path. – Craig Ringer Mar 30 '15 at 14:32
  • unix_socket_directories= /tmp – xav Mar 31 '15 at 11:44

3 Answers3

3

You cannot use /tmp to store sockets for interprocess communication in this scenario, because Apache uses private /tmp directories, a security feature that ensures that a process can only see its own /tmp directory; it cannot see what other processes write into /tmp because those other processes are actually writing into different directories.

This means that Apache cannot see the PostgreSQL socket.

You will need to continue using a local TCP connection.

You should also not disable SELinux, and use the correct boolean to allow the web server to talk to the database.

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
1

I'm mostly a fan of using local TCP connections as Michael Hampton pointed out, however you can manually specify another directory and / or symbolically link to another location that'll work around this issue.

For example:

mkdir /var/pgsql_socket/ 
ln -s /tmp/.s.PGSQL.5432 /var/pgsql_socket/

And point Apache at /var/pgsql_socket

Tim Brigham
  • 15,465
  • 7
  • 72
  • 113
1

Solved by editing /var/lib/pgsql/9.3/data/postgresql.conf

unix_socket_directories = '/tmp/var/pgsql_sock'

Then issued:

mkdir /var/pgsql_sock/

chown postgres:postgres  /var/pgsql_sock

edited setting.py in my django app .....HOST='/var/pgsql_sock'

Now it works fine with httpd.service

Alexander Farber
  • 714
  • 4
  • 16
  • 38
xav
  • 21
  • 5