Creating & Managing systemd Services
Advancedv1.0.0
Create production-ready systemd services — unit file structure, security directives, dependency management, automatic restarts, logging with journald, and timer-based scheduling.
Content
Overview
systemd is the init system and service manager for modern Linux. It manages service lifecycle (start, stop, restart), handles dependencies, provides logging via journald, and supports security sandboxing. Every production application should run as a systemd service.
Why This Matters
- -Automatic restart on crash — your app stays running without manual intervention
- -Boot-time startup — services start in the right order
- -Security sandboxing — limit what a service can access
- -Centralized logging — journald captures all output
Creating a Service
Step 1: Write the Unit File
Step 2: Create the Service User
Step 3: Enable and Start the Service
Step 4: View Logs with journald
Step 5: systemd Timers (Modern Cron)
Best Practices
- -Always run services as a dedicated user (never root)
- -Use security directives (ProtectSystem, PrivateTmp, NoNewPrivileges)
- -Set resource limits (MemoryMax, CPUQuota) to prevent runaway processes
- -Use EnvironmentFile for secrets (not Environment for sensitive values)
- -Use Type=notify for services that signal readiness
- -Set RestartSec to avoid tight restart loops on persistent failures
Common Mistakes
- -Running services as root when a dedicated user would work
- -Using nohup or screen instead of systemd (no auto-restart, no logging)
- -Not setting Restart=on-failure (service dies and stays dead)
- -Hardcoding secrets in the unit file (readable by all)
- -Forgetting daemon-reload after changing unit files
FAQ
Discussion
Loading comments...