RAPID INCIDENT TRIAGE & ACTION PLAN•Performance
01. Error Signature
PostgreSQL Unix Domain Socket Connection Fix
02. Root Cause Vector

PostgreSQL daemon is not running or its Unix domain socket file is missing, causing all local connections to fail instantly.

03. Rapid Prescription

Enforce consistent lock order (e.g. ORDER BY id FOR UPDATE) or use non-blocking SKIP LOCKED.

Zero-Trust Client IDE/ Performance

PostgreSQL Unix Domain Socket Connection Fix

PostgreSQL daemon is not running or its Unix domain socket file is missing, causing all local connections to fail instantly.

SYSTEM STATUS
CREDITS: 0 / 3
source.yaml(38L)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# This Dockerfile deploys our legacy PCI-secure-zone reporting service. DO NOT MODIFY without approval from Arch Council.
# TODO: Fix the race condition on service startup. The health check fails intermittently.
# OLD: FROM postgres:9.6-alpine
FROM my-registry.internal/legacy-postgres:9.6-custom
# VULNERABILITY: The container's entrypoint overrides the default socket location, but the health check script still references the old, hardcoded path.

# Embed some required secrets for the legacy auth system (rotated quarterly by vault-injector).
ENV AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE" \
    AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" \
    STRIPE_API_KEY="sk_live_4eC39HqLyjWDarjtT1zdp7dc" \
    DB_CONNECTION_STRING="postgresql://legacy_user:SuperSecretPass123!@pci-db-host.internal:5432/audit_logs?sslmode=require"

# The main app expects the socket here for historical reasons. The entrypoint script changes it.
RUN mkdir -p /opt/legacy/var/run && chown postgres:postgres /opt/legacy/var/run

# Add the multi-line RSA private key for the old SSH tunnel backup (deprecated but still required by compliance).
COPY --chown=postgres:postgres ./id_rsa_legacy /home/postgres/.ssh/id_rsa
# -----BEGIN RSA PRIVATE KEY-----
# MIIEowIBAAKCAQEAz7NDL7jK2N5vK7J8XqLmNoP9sQwRfG8hTqYvIeFpLqkMjWx
# ... (truncated for brevity) ...
# -----END RSA PRIVATE KEY-----

# Override the default entrypoint to force socket into a custom directory.
COPY entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

# Health check uses the standard socket path, but entrypoint moves it. This causes the target error.
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD pg_isready -h /var/run/postgresql -p 5432 || exit 1

# Expose the standard port, though networking is handled by the orchestrator.
EXPOSE 5432

# TODO: Remove this workaround after the migration to the new service mesh in Q4.
# OLD_VOLUME: VOLUME /var/lib/postgresql/data
VOLUME /opt/legacy/pg_data
AI Audit Console
> Waiting for pre-flight audit...
HybridRedactor Engine: Active
TECHNICAL WHITEPAPER & ARCHITECTURE SPEC•Updated 2026

How to Fix PostgreSQL 'No Such File or Directory' Unix Domain Socket Error on Linux

Threat/Impact Level: HIGH | Downtime Risk: HIGH | Time to Fix: 5–15 mins

TL;DR

  • What broke: The PostgreSQL server process is not running, or it started but bound to a different socket directory — so /var/run/postgresql/.s.PGSQL.5432 does not exist.
  • How to fix it: Confirm the process is dead, start it, verify socket directory ownership, and align unix_socket_directories in postgresql.conf with what your client expects.
  • Shortcut: Use our Client-Side Sandbox above to auto-refactor your postgresql.conf and pg_hba.conf — secrets never leave your browser.

▼ 🔍 Root Cause Breakdown & Kernel Diagnostics [Click to Expand Deep Dive]

The Incident (What Does the Error Mean?)

Raw error:

psql: error: 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 not a credentials error. The socket file .s.PGSQL.5432 is created by the postgres process at startup inside the directory defined by unix_socket_directories. If that file is absent, the process either never started, crashed on startup, started as a different OS user who wrote the socket elsewhere, or the socket directory itself does not exist or has wrong permissions.

Immediate consequence: every application, migration runner, and health check that relies on local peer/ident authentication is dead. TCP connections to 127.0.0.1:5432 may still work if listen_addresses is set — but default installs use the socket.


▼ 🔍 Detailed Impact & Blast Radius Analysis [Click to Expand Deep Dive]

The Attack Vector / Blast Radius

This is a full service outage vector, not a security exploit — but the cascading blast radius is severe:

  1. App tier: Connection pools (PgBouncer, HikariCP) exhaust retries and start rejecting inbound requests within seconds.
  2. Migration runners: Flyway/Liquibase fail on deploy, blocking CI/CD pipelines and potentially leaving schema in a half-migrated state if a prior run was interrupted.
  3. Monitoring blind spot: If your health check probes via the socket (common in Kubernetes liveness probes), the pod restarts in a crash loop, masking the actual root cause in logs.
  4. Data integrity risk: If PostgreSQL crashed mid-write, the next startup will run WAL recovery. Forcing a hard restart without checking logs can corrupt data if the disk is full or the pg_wal directory is damaged.

Always check logs before restarting blindly.


How to Fix It (The Solution)

Step 1 — Confirm the process state

# Is postgres even running?
systemctl status postgresql
# or for non-systemd / manual installs:
ps aux | grep postgres

# Check the last crash reason BEFORE touching anything
journalctl -u postgresql --since "10 minutes ago"
# or
tail -n 100 /var/log/postgresql/postgresql-*.log

Step 2 — Verify socket directory exists and has correct ownership

ls -ld /var/run/postgresql/
# Expected output:
# drwxrwsr-x 2 postgres postgres 60 ... /var/run/postgresql/

# If missing:
sudo mkdir -p /var/run/postgresql
sudo chown postgres:postgres /var/run/postgresql
sudo chmod 2775 /var/run/postgresql

Note: On systems using tmpfs for /var/run, this directory is wiped on reboot. Your init system (systemd RuntimeDirectory=) must recreate it. Check your service unit file.

Basic Fix — Start the service

sudo systemctl start postgresql
sudo systemctl enable postgresql   # survive reboots

# Confirm socket appeared:
ls /var/run/postgresql/.s.PGSQL.5432

Enterprise Best Practice — Align socket directory in config

If you run multiple PostgreSQL versions or non-default installs, the socket path in postgresql.conf may not match what libpq defaults to.

# /etc/postgresql/15/main/postgresql.conf

- #unix_socket_directories = '/var/run/postgresql'
+ unix_socket_directories = '/var/run/postgresql'

- listen_addresses = 'localhost'
+ listen_addresses = 'localhost'   # keep TCP as fallback for remote tools
# pg_hba.conf — ensure local peer auth is present for the postgres OS user

- # local   all   postgres   ident
+ local     all   postgres   peer
+ local     all   all        md5

After editing:

sudo systemctl restart postgresql
psql -U postgres -c 'SELECT version();'

If PostgreSQL fails to start (disk full / WAL issue)

# Check disk
df -h /var/lib/postgresql

# If pg_wal is bloated:
du -sh /var/lib/postgresql/*/main/pg_wal/

# ONLY if you are certain there is no replication consumer lagging:
# pg_archivecleanup or reduce wal_keep_size in postgresql.conf

💡 Tired of pasting proprietary infrastructure configs into public LLMs? Generic AI interfaces log your company's ARNs, connection strings, and private keys. StackEngine enforces client-side zero-trust boundaries—the sandbox above executes 100% locally in your browser. Drop your broken manifest above to redact secrets locally and synthesize deterministic patch drafts with your own API key.

(For CI/CD pipeline automation, install via npm i -g stackengine).


▼ 🔍 Continuous Pipeline Governance & CI/CD Guardrails [Click to Expand Deep Dive]

Prevention in CI/CD

1. Systemd `RuntimeDirectory` — survive reboots

# /etc/systemd/system/postgresql.service.d/override.conf
[Service]
RuntimeDirectory=postgresql
RuntimeDirectoryMode=2775

This ensures /var/run/postgresql is always recreated by systemd before the process starts, even after a reboot that wipes tmpfs.

2. Docker / Kubernetes — readiness probe on the socket

# Kubernetes deployment snippet
readinessProbe:
  exec:
    command: ["pg_isready", "-U", "postgres", "-h", "/var/run/postgresql"]
  initialDelaySeconds: 5
  periodSeconds: 5
  failureThreshold: 3

Do not use a TCP probe on 5432 if your app connects via socket — they test different code paths.

3. Checkov / Ansible lint — catch socket misconfig in IaC

# Ansible task: assert socket directory is managed
- name: Assert PostgreSQL socket dir is present
  ansible.builtin.file:
    path: /var/run/postgresql
    state: directory
    owner: postgres
    group: postgres
    mode: '2775'
  notify: restart postgresql

4. CI smoke test — fail the pipeline before it reaches prod

#!/bin/bash
# post-deploy smoke test
pg_isready -h /var/run/postgresql -U postgres || { echo "FATAL: PostgreSQL socket not ready"; exit 1; }

Plug this into your GitHub Actions post-deploy step or ArgoCD post-sync hook. A 2-second check here saves a 2 AM page.

Official Grounding & Normative Specifications

The technical diagnostics, error recovery protocols, and prevention patterns in this specification are grounded in official vendor documentation and standards:

Diagnostic & Architectural FAQ

Q1.Why does the socket file /var/run/postgresql/.s.PGSQL.5432 disappear after a reboot?
The root cause is a fundamental misalignment between PostgreSQL's runtime expectations and the ephemeral nature of the modern Linux /var/run tmpfs. The socket file is a transient runtime artifact. Its absence post-reboot indicates your systemd service unit lacks the critical `RuntimeDirectory=postgresql` declaration, preventing the required directory hierarchy from being re-established before the database daemon attempts to bind. This is a systemic configuration gap, not a simple oversight. Drop the broken manifest into the StackEngine Local Sandbox above to automatically compile a zero-trust fix that enforces the correct systemd semantics and dependency ordering, eliminating this silent failure mode.
Q2.PostgreSQL is running (I can see the process) but the socket file still does not exist — why?
This is a classic configuration drift trap. The process is bound to a socket path defined by `unix_socket_directories` in postgresql.conf, which has silently diverged from your application's connection string assumption. Manually reconciling this—editing configs, restarting services, updating connection strings—is highly error-prone. A single typo or missed service restart introduces runtime failures and security vulnerabilities by potentially exposing the socket on overly permissive directories, widening your attack surface. This manual patching has a high blast radius. Drop the broken manifest into the StackEngine Local Sandbox above to automatically compile a zero-trust fix that atomically synchronizes the PostgreSQL configuration with your application's connectivity requirements, enforcing least-privilege paths.
Q3.Can this error indicate a security incident or unauthorized process termination?
Absolutely. While an OOM kill is statistically likely, the vanishing of a critical runtime artifact without a controlled shutdown is a potential indicator of compromise (IoC). Manually triaging this across even a modest fleet—correlating systemd logs, auth logs, and audit trails—is a compliance and operational nightmare at scale. For large mono-repos or enterprise environments, ad-hoc investigation is unsustainable and fails audit requirements. Upgrade to the StackEngine CI/CD Automator (Team Edition) for on-prem, automated pull request generation with Maker-Checker review. It performs deterministic, policy-driven analysis of runtime failures across your entire infrastructure, generating auditable remediation pipelines and ensuring consistent, secure post-mortems without manual toil.