Writing Systemd Service Files for Your Applications

A template for running your applications as proper systemd services.

Key Insights

  • Systemd handles logging, restarts, dependencies, and resource limits — don’t reinvent this with screen or nohup
  • Use EnvironmentFile for secrets, MemoryMax for resource limits, and TimeoutStopSec for graceful shutdowns
  • Hardening directives (ProtectSystem, NoNewPrivileges, PrivateTmp) add meaningful security with minimal effort

If you’re running applications on Linux servers, systemd is the standard process manager. Here’s how to write service files that handle the common cases.

Basic Service File

# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target postgresql.service
Wants=postgresql.service

[Service]
Type=exec
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/server
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Environment Variables

[Service]
EnvironmentFile=/opt/myapp/.env
# Or inline:
Environment=PORT=8080
Environment=LOG_LEVEL=info

Resource Limits

[Service]
MemoryMax=512M
CPUQuota=200%
LimitNOFILE=65536

Graceful Shutdown

[Service]
ExecStop=/bin/kill -SIGTERM $MAINPID
TimeoutStopSec=30
KillMode=mixed

Common Commands

sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo journalctl -u myapp -f

Hardening

[Service]
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/myapp/data
PrivateTmp=yes

Systemd handles logging, restarts, dependencies, and resource limits. Don’t reinvent this with screen sessions or nohup.

Liked this? There's more.

Every week: one practical technique, explained simply, with code you can use immediately.