Skip to content

systemd socket activation: writing a .socket unit paired with a .service

Set up systemd socket activation so PID 1 owns the listening socket and hands it to your daemon over the LISTEN_FDS protocol, keeping connections queued in the kernel accept queue across a service restart.

systemd socket activation splits a network service in two: a .socket unit that owns the listening file descriptor, and a .service unit that inherits it. Because PID 1 creates and binds the socket before the daemon ever runs — and keeps holding it while the daemon is stopped, restarted, or crashed — the listening port never disappears. A client that connects during a restart completes the TCP handshake into the kernel’s accept queue and waits there instead of getting ECONNREFUSED. This guide converts a plain TCP service to socket activation, proves the difference with a live client loop across a systemctl restart, then covers the on-demand and per-connection variants, unix socket ownership for an nginx upstream, and what to do when your daemon does not speak the protocol at all.

What you’ll accomplish

  • Write a matched greeter.socket and greeter.service pair where systemd binds 127.0.0.1:9110 and the daemon accepts on the inherited descriptor.
  • Watch a client loop survive a systemctl restart with a delay instead of a refusal, and read the pending count out of ss.
  • Choose between the two Accept= modes: one long-lived process for all connections, or one instance per connection.
  • Turn a rarely-used daemon into an on-demand one that starts on first connection and exits when idle.
  • Hand an AF_UNIX socket to an app server with the right owner and mode so nginx can reach it without running as root.

Prerequisites

  • A Linux host with systemd 249 or newer and root via sudo. Most of this works back to systemd 235; the Triggers: line in systemctl status is newer. Check with systemctl --version.
  • Python 3.8 or newer for the worked example, only because socket.create_server() keeps it short. The mechanism is language-agnostic.
  • netcat and ss. On Debian/Ubuntu that is netcat-openbsd and iproute2; on RHEL-family hosts, nmap-ncat and iproute. The two netcat flavours print different error text, which matters when you read the failure output below.
  • A daemon that supports the protocol, or the willingness to wrap one. This is the real prerequisite: the program must look at LISTEN_FDS and accept on the descriptors it was given. Many do (systemd’s own services, D-Bus, Cockpit, Gunicorn, uWSGI, Docker); many do not. The last section covers the wrapper for the rest.
  • Comfort editing units under /etc/systemd/system/. If you are also tightening those units, hardening a systemd service unit pairs directly with this — socket activation is what makes PrivateNetwork=yes practical, since the daemon no longer binds anything itself.

How it works

A normal daemon calls socket(), bind(), and listen() itself, after the process starts. That leaves a window — from the moment the old process closes its socket to the moment the new one finishes binding — when nothing is listening on the port. During that window the kernel answers every incoming SYN with an RST, and the client’s connect() fails with ECONNREFUSED.

Socket activation moves those three calls into PID 1. systemd binds and listens at boot, then holds that descriptor for the lifetime of the socket unit, independent of the service.

Comparison of a plain service where the listening port disappears during a restart and the client gets ECONNREFUSED, against a socket-activated service where systemd keeps the socket bound and the kernel accept queue holds the connection until the restarted daemon drains it

The important detail is what a listening socket does when nobody is calling accept(). The kernel completes the three-way handshake on its own and parks the finished connection in the accept queue, whose depth comes from the backlog argument to listen(2). connect() on the client side returns success, and the client can even send its request; it just gets no answer until some process accepts. A restart therefore turns a refusal into latency, bounded by that queue: once it fills, the kernel drops further SYNs, clients retry with backoff, and a long enough restart still fails. This is a much better failure mode, not the absence of one.

Backlog= in the socket unit is what gets passed to listen(2). It defaults to 4294967295, which the kernel silently clamps to net.core.somaxconn (4096 on current kernels).

Step-by-step

1. Write a daemon that can use an inherited descriptor. Save this as /usr/local/bin/greeter. It checks LISTEN_PID and LISTEN_FDS, uses fd 3 if they are set, and falls back to binding its own socket if they are not — which keeps it runnable by hand.

#!/usr/bin/env python3
import os
import socket
import sys
import time

SD_LISTEN_FDS_START = 3

def inherited_listener():
    # LISTEN_PID guards against fds leaking into a child process
    if os.environ.get("LISTEN_PID") != str(os.getpid()):
        return None
    if int(os.environ.get("LISTEN_FDS", "0")) < 1:
        return None
    return socket.socket(fileno=SD_LISTEN_FDS_START)

sock = inherited_listener()
if sock is None:
    print("binding my own socket", file=sys.stderr, flush=True)
    sock = socket.create_server(("127.0.0.1", 9110), backlog=128)
else:
    print("inherited fd 3 from the service manager", file=sys.stderr, flush=True)

time.sleep(3)  # stand-in for a slow warm-up: cache load, JIT, migrations

while True:
    conn, _ = sock.accept()
    with conn:
        conn.sendall(f"served by pid {os.getpid()}\n".encode())
sudo chmod 0755 /usr/local/bin/greeter

On Linux, socket.socket(fileno=...) reads the real family and type off the descriptor, so this works unchanged when you switch to a unix socket later.

2. Start with the plain service, so you can see the problem. Write /etc/systemd/system/greeter.service:

[Unit]
Description=Greeter demo

[Service]
ExecStart=/usr/local/bin/greeter
DynamicUser=yes
Restart=on-failure

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now greeter.service
ss -lntp 'sport = :9110'

The ss output shows a LISTEN row whose Process column names the python3 process and its PID — the daemon owns the socket.

3. Run a client loop and restart the service. In a second terminal:

while :; do
  printf '%s ' "$(date +%T)"
  nc -w 10 127.0.0.1 9110 || echo "connect failed"
  sleep 0.5
done

You get a line every half second naming the server PID. Now, in the first terminal, run sudo systemctl restart greeter.service. The loop prints roughly six consecutive failures over the next three seconds; the wording depends on your netcat build (openbsd-netcat says connect to 127.0.0.1 port 9110 (tcp) failed: Connection refused, nmap-ncat says Ncat: Connection refused.), but either way the connection was rejected outright. Leave the loop running.

4. Add the socket unit. Create /etc/systemd/system/greeter.socket:

[Unit]
Description=Greeter demo socket

[Socket]
ListenStream=127.0.0.1:9110
Accept=no
Backlog=512
FileDescriptorName=greeter-http

[Install]
WantedBy=sockets.target

ListenStream= with an address:port gives a TCP listener; a value starting with / gives an AF_UNIX stream socket. Accept=no is the default and almost always the mode you want: systemd passes the listening socket to one long-lived service instance, which does its own accept() calls. FileDescriptorName= labels the descriptor so a daemon calling sd_listen_fds_with_names() can tell several sockets apart; the default is the socket unit’s own name.

Note what is not in the file: nothing points at greeter.service. systemd derives the service name from the socket name, and Service= exists only to break that convention.

5. Trim the service unit and swap which unit is enabled.

[Unit]
Description=Greeter demo
Requires=greeter.socket
After=greeter.socket

[Service]
ExecStart=/usr/local/bin/greeter
DynamicUser=yes
Restart=on-failure

The [Install] section is gone on purpose: the socket gets enabled at boot, not the service. The explicit Requires=/After= stop anyone starting the service without its socket and silently falling back to binding its own port.

sudo systemctl daemon-reload
sudo systemctl disable --now greeter.service
sudo systemctl enable --now greeter.socket
systemctl status greeter.socket
● greeter.socket - Greeter demo socket
     Loaded: loaded (/etc/systemd/system/greeter.socket; enabled; preset: enabled)
     Active: active (listening) since Thu 2026-08-06 10:12:04 UTC; 2s ago
   Triggers: ● greeter.service
     Listen: 127.0.0.1:9110 (Stream)

active (listening) with the service not yet running is the whole point. Your client loop, still running in the other terminal, will have triggered greeter.service on its next iteration.

6. Confirm the descriptor really is inherited. The handoff is a small, exact protocol.

Sequence showing systemd creating and binding the socket, the kernel queueing the first connection, systemd starting the service with fd 3 already open and LISTEN_FDS set, and the daemon verifying LISTEN_PID before accepting on the inherited descriptor

sudo journalctl -u greeter.service -n 5 --no-pager
sudo systemctl show greeter.service -p MainPID --value

The journal line reads inherited fd 3 from the service manager, not binding my own socket. To see the environment systemd set, read it out of the running process:

sudo tr '\0' '\n' < /proc/$(systemctl show greeter.service -p MainPID --value)/environ | grep LISTEN
LISTEN_PID=8412
LISTEN_FDS=1
LISTEN_FDNAMES=greeter-http

LISTEN_FDS=1 means exactly one descriptor was passed, starting at fd 3 (SD_LISTEN_FDS_START). LISTEN_PID is the guard: sd_listen_fds() refuses the descriptors unless it matches getpid(), so a forked child cannot accidentally claim them. Several ListenStream= lines in one socket unit give you fds 3, 4, 5 in file order — but when multiple socket units activate the same service, the order is explicitly undefined and you must use sd_listen_fds_with_names() with FileDescriptorName=.

7. Make it on-demand. For a daemon used a few times a day, let systemd start it on first connection and let it exit when idle. Add a drop-in:

sudo systemctl edit greeter.service
[Service]
Restart=no

Then stop the service but leave the socket up:

sudo systemctl stop greeter.service
systemctl is-active greeter.service greeter.socket
inactive
active

The next connection starts it again. The one setting that ruins this is Restart=always: systemd brings the daemon straight back up after every idle exit, giving you a restart loop instead of on-demand activation.

8. Use Accept=yes only when the workload fits it. Accept=yes makes systemd call accept() itself and spawn one service instance per connection, passing the connection socket rather than the listener. It needs a template unit, greeter@.service, and an inetd-style program reading stdin:

[Socket]
ListenStream=127.0.0.1:9111
Accept=yes
MaxConnections=64
[Service]
ExecStart=/usr/local/bin/greeter-inetd
StandardInput=socket
DynamicUser=yes

Each connection costs a full unit start: fork, exec, cgroup setup. Fine for an admin tool contacted a few times an hour, wrong for anything with real traffic. MaxConnections= defaults to 64 and connections past it are refused, so a busy port under Accept=yes starts rejecting clients — the behaviour you adopted socket activation to avoid.

9. Hand a unix socket to nginx with the right ownership. For an app server behind a reverse proxy, an AF_UNIX socket skips the TCP stack and lets you use filesystem permissions instead of a bind address. SocketMode= defaults to 0666, which is world-writable — set it explicitly:

[Socket]
ListenStream=/run/greeter/app.sock
SocketUser=root
SocketGroup=www-data
SocketMode=0660

Pair that with RuntimeDirectory=greeter in the service unit so /run/greeter is created and cleaned up for you. nginx (running as www-data) connects through the group bit; no other local account can:

upstream greeter { server unix:/run/greeter/app.sock; }

This is the pattern people know from PHP-FPM, with one difference worth stating plainly: PHP-FPM creates its own socket and owns it via listen.owner, listen.group, and listen.mode in the pool config. SocketUser= and friends apply only when systemd is the one creating the node.

Validate it works

With greeter.socket enabled and the client loop running, restart the service and watch the queue rather than the errors:

sudo systemctl restart greeter.service; ss -lnt 'sport = :9110'
State   Recv-Q  Send-Q   Local Address:Port   Peer Address:Port
LISTEN  3       512          127.0.0.1:9110        0.0.0.0:*

On a listening socket, Recv-Q is the number of established connections waiting to be accepted and Send-Q is the configured backlog — so 3 is three clients parked in the kernel while the daemon warms up, and 512 confirms Backlog= took effect. The client loop shows a pause of about three seconds with no “connect failed” line, then resumes with a new PID. Compare that to step 3.

Two more checks for the runbook:

systemctl list-sockets --no-pager
LISTEN            UNIT            ACTIVATES
127.0.0.1:9110    greeter.socket  greeter.service
sudo systemctl stop greeter.service && ss -lntp 'sport = :9110'

With the service stopped, the LISTEN row is still there and its Process column now reads users:(("systemd",pid=1,fd=25)). PID 1 is holding the port.

Troubleshooting

The service logs Address already in use (EADDRINUSE) on start. Something started greeter.service directly while the socket unit held the port, so the daemon’s fallback path tried to bind it a second time. SO_REUSEADDR does not help; it only bypasses TIME_WAIT. The Requires=greeter.socket from step 5 covers the common case — also check systemctl is-enabled greeter.service, which should report static or disabled, never enabled.

The daemon reports zero inherited descriptors. Nearly always a LISTEN_PID mismatch: ExecStart= points at a shell wrapper that forks the real binary instead of exec-ing it. Use exec "$@" in the wrapper, or drop the wrapper. The other cause is a sudo, su, or entrypoint layer in between, which scrubs the environment and closes the descriptors.

The socket unit goes to failed with a trigger-limit message. If the service crashes immediately, every queued connection re-triggers it, and systemd cuts that off: TriggerLimitBurst= defaults to 20 activations per TriggerLimitIntervalSec=2s for Accept=no sockets, 200 for Accept=yes. Fix the crash first with journalctl -u greeter.service -b, then systemctl reset-failed greeter.socket && systemctl start greeter.socket. Raising the limit only makes the crash loop faster.

nginx returns 502 with connect() to unix:/run/greeter/app.sock failed (13: Permission denied). Either SocketGroup= does not match the nginx worker user, SocketMode= is too restrictive, or a directory in the path is not traversable. Confirm with sudo -u www-data test -w /run/greeter/app.sock && echo ok. On SELinux hosts, a denial with correct-looking modes usually means a missing file context — check sudo ausearch -m avc -ts recent.

The unix socket file survives a stop. systemd leaves the node in place on purpose, so clients can still connect and re-trigger activation. If you genuinely need it gone, set RemoveOnStop=yes — but prefer RuntimeDirectory=, which puts the socket under /run and has systemd clean up the whole directory.

When this is the wrong approach

Socket activation removes the connection-refused window during a restart. It does not remove the restart. Requests still wait for the daemon to come back, in-flight requests on the old process are still cut off unless it handles SIGTERM properly, and a slow-starting service simply converts refusals into timeouts. If your requirement is that no client ever sees added latency, you need two instances behind a load balancer with connection draining, not a .socket unit.

It is also the wrong tool when the daemon does not implement the protocol and you cannot patch it. The escape hatch is systemd-socket-proxyd, which is socket-activated itself and forwards to a normal listener: ListenStream=80 in proxy-to-app.socket, ExecStart=/usr/lib/systemd/systemd-socket-proxyd 127.0.0.1:8080 with Type=notify in proxy-to-app.service, and the real daemon keeps binding 127.0.0.1:8080. Handy for on-demand start of a heavy service (add --exit-idle-time=5min), but it puts a copying proxy in the data path and drops SO_PEERCRED and SCM_RIGHTS, so it does not suit anything doing peer-credential authentication.

And on Kubernetes or any container platform with readiness gates and rolling updates, that layer solves the same problem where you also get multiple replicas. Socket activation earns its keep on single-host services: the app server behind a reverse proxy, an internal admin daemon, a metrics exporter. For scheduled work rather than listening services, systemd timers versus cron is the relevant comparison — activation by time and activation by connection get conflated often.

The reference for every option above is systemd.socket(5); the client side of the protocol is documented in sd_listen_fds(3).

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.