Systemd socket unit

Why is it useful

The socket unit will make systemd listen on a specific socket and start a service on request. You can start a network server in a couple of minutes using a simple script as an engine. You can get parallel execution of tasks, limited by the count or execution time.

Pay attention to the security aspect if you are implementing a network server. Usually, the firewall and selinux will not let you do this easily. But after you break the security, don't forget to build it again. To make this demo a bit safer, I'll be using Unix sockets.

Unit files

Two unit files are involved in this solution, one describes the socket, and the second the service to be started.

# cat /etc/systemd/system/myDemo.socket
[Unit]
Description=Listen to Unix socket demo

[Socket]

# Start service inctance for every connection; unit should be a template, like myDemo@.service
Accept=yes
# One service can serve multiple connections:
#Accept=no
#Service=sshd

# TCP listen on port 1111 ipv6:
#ListenStream=1111
# TCP listen on port 1111 ipv4:
#ListenStream=0.0.0.0:1111
# UDP:
#ListenDatagram=
# Unix socket:
ListenSequentialPacket=/run/systemd/myDemo

# Some security by ACL:
#SocketUser=myuser
#SocketGroup=mygroup
#SocketMode=0600

# Can serve only 5 request simultaniously
MaxConnections=5

Our service is a simple command and cannot handle multiple connections. Therefore, you should use the Accept=yes parameter. Because of this, a new instance of the service will be started for each connection. In this mode, the service unit file must have the same name as the socket unit file and be a template (end with @ symbol).

# cat /etc/systemd/system/myDemo@.service
[Unit]
Description=Show uptime by request

[Service]
StandardInput=socket
ExecStart=-/usr/bin/uptime
RuntimeMaxSec=5min
IPAddressDeny=any
RestrictAddressFamilies=AF_UNIX
#User=
#Group=

Pay attention to a couple of parameters that limit the maximum number of simultaneously running services and the maximum time for its execution. This will minimally protect the resources of your machine.

Test it works

Start the socket unit. There are no need to start or enable the service unit. It will be launched by the socket unit.

# systemctl start myDemo.socket

The socat tool allows you to work with different types of sockets right from the command line.

# socat - UNIX-CLIENT:/run/systemd/myDemo
 15:09:11 up 18:02,  5 users,  load average: 0.95, 0.73, 0.64

Updated on Tue Feb 28 21:27:23 IST 2023 More documentations here