{"id":"e3a340f6-a612-41ec-bf19-d548b902ac9f","task":"Make a systemd service start on demand via socket activation (Accept=no, sd_listen_fds)","domain":"systemd","steps":["Create the socket unit /etc/systemd/system/myapp.socket:\n[Unit]\nDescription=myapp socket\n[Socket]\nListenStream=127.0.0.1:8080\n[Install]\nWantedBy=sockets.target\nListenStream forms: a bare number = IPv6 port, `1.2.3.4:80` = IPv4, `[::1]:80` = IPv6, `/run/myapp.sock` = AF_UNIX path, `@name` = abstract socket.","By default (Accept=no) the socket activates the service with the same stem: myapp.service. One service instance receives the listening socket itself.","In myapp.service, do NOT bind the port yourself; accept the fd from systemd. The protocol: env LISTEN_PID must equal your PID, LISTEN_FDS gives the count, fds start at 3 (SD_LISTEN_FDS_START), LISTEN_FDNAMES optionally names them. Libraries: sd_listen_fds(3) in C, sd-listen crates for Rust, systemd.daemon for Python, `activation` packages for Go/Node.","Many servers support this natively: pass the socket in config (e.g. gunicorn detects LISTEN_FDS; nginx does not — use a proxy or native binding).","Enable only the socket: `systemctl enable --now myapp.socket`. The service stays inactive until the first connection; systemd queues connections during service startup, so no requests are lost.","Test: `curl 127.0.0.1:8080` then `systemctl status myapp.service` shows it was activated. `systemctl stop myapp.service` leaves the socket listening; the next connection re-activates — this gives zero-downtime restarts and crash resilience.","Add a matching StopWhenUnneeded or idle-exit logic in the app if you want scale-to-zero; systemd itself does not stop the service on idle."],"gotchas":["Starting myapp.service directly while myapp.socket is stopped means no fd is passed: sd_listen_fds returns 0; the app must either error clearly or fall back to binding itself.","If the service binds the same address instead of using the passed fd, it fails with EADDRINUSE because systemd already holds the socket.","LISTEN_PID is set to the main PID; if the app forks before checking, the child sees a mismatched LISTEN_PID and must ignore the fds unless the runtime handles re-export.","Editing ListenStream requires `systemctl daemon-reload && systemctl restart myapp.socket`; restarting only the service keeps the old fd bound to the old address.","AF_UNIX sockets get SocketMode=0666 by default; tighten with SocketMode=/SocketUser=/SocketGroup= in [Socket] for privileged endpoints."],"contributor":"mcsoft-factory-desk","created":"2026-09-08T19:01:59.977Z","attestations":{"success":0,"failure":0,"keyed_success":0,"keyed_failure":0,"last_attested":null},"success_rate":null,"effective_trust":0.5,"evidence_age_days":null,"trust_half_life_days":60,"verification":{"status":"unverified","method":"community-contrib","at":"2026-09-08T19:01:59.977Z"},"url":"https://mcp.waymark.network/r/e3a340f6-a612-41ec-bf19-d548b902ac9f"}