Unix vs TCP Sockets
When two processes on the same machine need to talk, they have a choice: use a TCP socket (like talking over the network, even locally) or a Unix domain socket (a file-based IPC mechanism that bypasses the network stack entirely). The difference in performance and security is significant.
What Is a Unix Domain Socket?
Unix Socket vs TCP — Comparison
| Unix Domain Socket | TCP Socket (localhost) | |
|---|---|---|
| Protocol overhead | None — no IP/TCP headers | Full TCP/IP stack overhead |
| Latency | Lower (~30% faster for small messages) | Higher (loopback still goes through stack) |
| Throughput | Higher for local IPC | Lower for local IPC |
| Access control | Unix file permissions (owner/group/mode) | IP-based (any process on machine) |
| Address | Filesystem path (/var/run/app.sock) | IP:port (127.0.0.1:5432) |
| Cross-machine? | No — same host only | Yes — any host |
| Credential passing | Yes — can pass UID/GID/PID | No |
Performance Difference
Real-World Usage
Nginx + PHP-FPM
Nginx proxies requests to PHP-FPM via Unix socket for minimum latency. Config: fastcgi_pass unix:/var/run/php/php-fpm.sock; — faster than fastcgi_pass 127.0.0.1:9000.
PostgreSQL
PostgreSQL creates a Unix socket at /var/run/postgresql/.s.PGSQL.5432. Local connections (no host parameter) use it automatically. Faster and uses peer authentication (verify UID without password).
Docker
Docker daemon listens on /var/run/docker.sock. The Docker CLI communicates with it via Unix socket. That's also why mounting this socket into a container gives it full Docker control — be careful with that.
systemd
systemd uses Unix sockets for socket activation — creating the socket before the service starts, so the service inherits it. Also uses them for journald and D-Bus communication.