How to Create a systemd Service on Linux
Manage background processes with systemd unit files.
Systemd is the init system used by most modern Linux distributions. Creating a custom service lets you run applications automatically at startup, manage them with systemctl, and ensure they stay alive. This deep dive explains how to write unit files, configure services, enable them at boot, and troubleshoot common issues.
Photo by Gabriel Heinzer on Unsplash
Step 1: Create a Unit File
A systemd unit file defines how your service should run. It lives in /etc/systemd/system for system‑wide services.
sudo nano /etc/systemd/system/myapp.service
Example configuration:
[Unit]
Description=My Node.js App
After=network.target
[Service]
ExecStart=/usr/bin/node /home/user/app.js
Restart=always
User=user
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
Explanation:
[Unit]: Metadata and dependencies.After=network.targetensures the service starts after networking is ready.[Service]: Defines how the process runs.ExecStartis the command,Restart=alwaysensures resilience,Usersets permissions.[Install]: Specifies when the service should start.multi-user.targetmeans it runs in normal multi‑user mode.
Step 2: Enable and Start
Once the unit file is created, reload systemd to recognize it, then enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp
Explanation:
daemon-reload: Reloads systemd configuration.enable: Ensures the service starts automatically at boot.start: Starts the service immediately.status: Shows logs and current state.
Step 3: Monitoring and Logs
Use journalctl to view logs:
journalctl -u myapp -f
This streams logs in real time. Combine with systemctl status for quick diagnostics.
Step 4: Best Practices
- Run services under a dedicated user for security.
- Use
Environment=variables for configuration. - Set
Restart=on-failureif you only want restarts on crashes. - Document your unit files with clear
Description.
Step 5: Troubleshooting
Common issues include:
- Permission errors: Ensure the
Userhas access to files. - ExecStart not found: Verify the path to your binary.
- Service won’t start at boot: Check
systemctl is-enabled myapp. - Debugging: Add
StandardOutput=journalandStandardError=journalto capture logs.
Conclusion
Creating a systemd service transforms scripts or apps into managed background processes. With unit files, auto‑start, logging, and restart policies, you gain reliability and control. Mastering systemd is essential for running production workloads on Linux.