A unix socket is a meeting point for two processes on one
machine. As with a network socket, the server listens and the
client connects, but the address is a file path such as /run/app/app.sock
instead of an IP and port. Data goes through the kernel and never reaches the
network.
Where you meet them: PostgreSQL listens on /var/run/postgresql/.s.PGSQL.5432
— psql without -h connects through it; Docker on /run/docker.sock;
systemd and D-Bus keep dozens of sockets in /run. An application behind
nginx often listens on a socket instead of a port: no port is taken, the
application cannot be reached from outside, and file permissions decide
access.
$ ls -l /run/app/app.sock
srwxr-xr-x 1 root root 0 Oct 20 10:04 /run/app/app.sock
s as the first letter is the "socket" type. The size is always 0: no data is
stored in the file.
Permissions: who can connect
To connect, a client needs write permission on the socket file and search
permission (x) on every directory in the path. Read permission is not needed.
The server creates the file, and the mode comes from its umask. A root
process with umask 022 creates srwxr-xr-x root root — only root can
connect. nginx connects as the www-data user:
| Socket permissions |
Can www-data connect? |
srwxr-xr-x root root |
no: others have no w |
srw-rw---- root www-data |
yes: the group has w |
srwxrwxrwx root root |
yes, and so can any user |
Mode 777 opens the socket to every process on the machine. Grant access
through a group the client belongs to, with mode 660 or 770.
Lifetime of a socket file
The server creates the file when it starts listening and should delete it on
exit. A crashed or killed process leaves the file behind: the path exists but
nobody listens. A client then gets Connection refused, and a new server start
gets Address already in use until the old file is removed.
/run lives in memory and is empty after a reboot. systemd creates the
directory for a service's socket: the line RuntimeDirectory=app in the unit
makes /run/app appear when the service starts and vanish when it stops.