A daemon is a background process that starts automatically at boot and runs without user interaction. Modern Linux distributions use systemd to manage daemons. This guide shows how to create a systemd service and, optionally, a legacy SysV init script.
Page
How to create a daemon service
Overview
Prerequisites
-
A Linux distribution with systemd (e.g., Ubuntu 20.04+, Debian 10+, CentOS 7+, Fedora)
-
Root or sudo privileges
-
An executable script or binary you want to run as a daemon
1. Prepare the Executable
Create a simple script to test the service. Save it as /usr/local/bin/hello.sh and make it executable:
#!/bin/bash
while true; do
echo "$(date) - Hello from daemon" >> /var/log/hello-daemon.log
sleep 60
done
sudo chmod +x /usr/local/bin/hello.sh
2. Write a systemd Service Unit
Create a file /etc/systemd/system/hello.service with the following content:
[Unit]
Description=Hello Daemon Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/hello.sh
Restart=on-failure
User=root
StandardOutput=append:/var/log/hello-daemon.log
StandardError=append:/var/log/hello-daemon.log
[Install]
WantedBy=multi-user.target
Tip: Use
Type=simplefor scripts that run in the foreground. If your program daemonizes itself, useType=forking.
3. Enable and Start the Service
-
Reload systemd to recognize the new unit
-
Enable the service to start at boot
-
Start the service now
sudo systemctl daemon-reload
sudo systemctl enable hello.service
sudo systemctl start hello.service
4. Manage the Service
<!-- Unsupported Notion block: table -->
5. Verify Automatic Startup
Reboot the machine and confirm the service is active:
sudo reboot
# After reboot
sudo systemctl status hello.service
Optional: Legacy SysV Init Script
For distributions without systemd, create an init script in /etc/init.d/hello:
#!/bin/sh
### BEGIN INIT INFO
# Provides: hello
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Hello daemon
### END INIT INFO
DAEMON=/usr/local/bin/hello.sh
PIDFILE=/var/run/hello.pid
case "$1" in
start)
echo "Starting hello..."
start-stop-daemon --start --background --make-pidfile --pidfile $PIDFILE --exec $DAEMON
;;
stop)
echo "Stopping hello..."
start-stop-daemon --stop --pidfile $PIDFILE
;;
restart)
$0 stop
$0 start
;;
status)
status_of_proc -p $PIDFILE $DAEMON hello && exit 0 || exit $?
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit 0
sudo chmod +x /etc/init.d/hello
sudo update-rc.d hello defaults
sudo service hello start
Common Pitfalls
-
Forgetting to
chmod +xthe script makes the service fail to start. -
Using the wrong
Typein the unit file can cause systemd to think the service has exited. -
Not reloading systemd after editing unit files (
daemon-reload).
You now have a functional daemon managed by systemd (or SysV init). Adjust paths, users, and restart policies to fit your application.