How do you write a simple systemd service file for your own app?
Create a .service file in /etc/systemd/system with a [Unit] description, a [Service] section giving ExecStart and a user, and an [Install] section with WantedBy=multi-user.target. Then run systemctl daemon-reload and systemctl enable --now name.
Explain it simply
A unit file tells systemd how to start, watch and stop your program, so it behaves like nginx or sshd instead of a script in a terminal.
Save this as /etc/systemd/system/myapp.service:
[Unit]
Description=My Node app
After=network.target
[Service]
User=deploy
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node server.js
Restart=on-failure
[Install]
WantedBy=multi-user.targetAfter=sets the start order.ExecStart=must use an absolute path.User=avoids running as root.Restart=on-failurerevives the app if it crashes.WantedBy=multi-user.targetis whatenablehooks into for normal boot.
Then run sudo systemctl daemon-reload so systemd re-reads files, and sudo systemctl enable --now myapp. Check with systemctl status myapp and journalctl -u myapp.
Example
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
systemctl status myapp --no-pager | head -3
# * myapp.service - My Node app
# Loaded: loaded (/etc/systemd/system/myapp.service; enabled)
# Active: active (running)What to say in the interview
"I write a unit in /etc/systemd/system with Unit, Service and Install sections, using an absolute ExecStart, a non-root User and Restart=on-failure. Then daemon-reload, enable --now, and I inspect it with status and journalctl -u."
Common mistakes
- Forgetting daemon-reload after editing a unit file.
- Using relative paths in ExecStart.