Socket-Activated Service
Implement systemd socket activation for on-demand service startup. Learn how socket units work, why they improve boot time, and how to configure Accept= for connection handling.
Detailed Explanation
On-Demand Services with Socket Activation
Socket activation is one of systemd's most powerful features. Instead of starting a service immediately at boot, systemd opens the listening socket and only starts the service when the first connection arrives.
The Socket Unit
[Unit]
Description=My Application Socket
[Socket]
ListenStream=8080
Accept=no
BindIPv6Only=both
[Install]
WantedBy=sockets.target
The Service Unit
[Unit]
Description=My Application Server
Requires=myapp.socket
[Service]
Type=simple
ExecStart=/usr/local/bin/myapp
User=appuser
Group=appuser
StandardOutput=journal
StandardError=journal
# Socket is passed as file descriptor 3
Environment="LISTEN_FDS=1"
How Socket Activation Works
- At boot, systemd creates the socket and listens on port 8080
- No service process is running — zero resource usage
- A client connects to port 8080
- Systemd accepts the connection and starts the service
- The socket file descriptor is passed to the service process
- The service handles the connection and all subsequent ones
Accept=no vs Accept=yes
Accept=no(default): Systemd passes the listening socket to one instance of the service. The service accepts connections itself. This is the standard mode for web servers.Accept=yes: Systemd accepts each connection and spawns a new service instance per connection (like inetd). The service name gets a template suffix:myapp@.service.
Benefits of Socket Activation
- Faster boot: Services start only when needed, reducing boot time
- Zero-downtime updates: The socket stays open while the service restarts
- On-demand startup: Rarely-used services don't consume resources until needed
- No port conflicts: systemd manages socket allocation
- Dependency resolution: Other services can depend on the socket being available
Application Support
The application must support receiving sockets from systemd. Libraries exist for most languages:
- Go:
github.com/coreos/go-systemd/activation - Python:
systemd.daemon.listen_fds() - Node.js:
sd-listen-fdspackage - Rust:
listenfdcrate - C:
sd_listen_fds()from libsystemd
Zero-Downtime Restart
# Socket stays open — no dropped connections
systemctl restart myapp.service
During the restart, incoming connections queue at the socket level. The new service instance picks them up once started.
Use Case
Running services that receive infrequent traffic but must respond quickly when requests arrive, such as internal APIs, development tools, or services that need zero-downtime restarts.