THE ONE GIANT

Contact us

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.target ensures the service starts after networking is ready.
  • [Service]: Defines how the process runs. ExecStart is the command, Restart=always ensures resilience, User sets permissions.
  • [Install]: Specifies when the service should start. multi-user.target means 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-failure if you only want restarts on crashes.
  • Document your unit files with clear Description.

Step 5: Troubleshooting

Common issues include:

  • Permission errors: Ensure the User has 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=journal and StandardError=journal to 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.