Lazy load services using Socket Activation
Lazy loading services allows services to only be started once they are needed.
This has many system benefits such as:
- Speed up startup time: only what is needed is started
- Increase linux performance as unused services are not started until they are needed
How it works
I connect to postgres on port 5432. This is the port the socket is listening on. When the socket receives traffic; the socket service will start postgres on port 5433 and proxy traffic from port 5432 to port 5433.
Proxy Socket
The proxy socket listens on an address and once it receives a connection it will activate the Socket Service
Location: /etc/systemd/system/postgresql-proxy.socket
[Socket]
ListenStream=127.0.0.1:5432
[Install]
WantedBy=sockets.target
Socket Service
When this service is started:
- The service it is proxying is started
- The connection of the socket is proxyed to the actual service
[Unit]
Requires=postgresql.service
After=postgresql.service
Requires=postgresql-proxy.socket
After=postgresql-proxy.socket
[Service]
ExecStart=/lib/systemd/systemd-socket-proxyd 127.0.0.1:5433
PrivateTmp=no
PrivateNetwork=no
Service
This can be considered the actual service which starts the program.
[Unit]
Description=PostgreSQL Server Docker Service
[Service]
Type=simple
ExecStart=/home/john/postgres/run.sh 5433
TimeoutStopSec=5
[Install]
WantedBy=multi-user.target
Finishing up
After creating the <program>.service, <program>-proxy.service and <program>-proxy.socket enable it with the following command:
sudo systemctl enable <program>-proxy.socket
It will automatically work every time upon reboot. You may need to start it this time only to test it
sudo systemctl start <program>-proxy.socket