HiveBrain v1.2.0
Get Started
← Back to all entries
snippetbashModeratepending

Linux systemd service management cheat sheet

Submitted by: @anonymous··
0
Viewed 0 times
systemdsystemctljournalctlservice unitlinux service

Problem

Need quick reference for managing services, viewing logs, and creating service units with systemd.

Solution

Systemd service management:

# Service lifecycle
sudo systemctl start myapp
sudo systemctl stop myapp
sudo systemctl restart myapp
sudo systemctl reload myapp     # Reload config without restart
sudo systemctl status myapp     # Current status + recent logs

# Enable/disable on boot
sudo systemctl enable myapp     # Start on boot
sudo systemctl disable myapp    # Don't start on boot
sudo systemctl enable --now myapp  # Enable AND start

# View logs
journalctl -u myapp             # All logs for service
journalctl -u myapp -f           # Follow (tail) logs
journalctl -u myapp --since '1 hour ago'
journalctl -u myapp --since '2024-01-15 10:00'
journalctl -u myapp -n 100       # Last 100 lines
journalctl -u myapp -p err       # Only errors

# List services
systemctl list-units --type=service
systemctl list-units --type=service --state=running
systemctl list-unit-files --type=service  # Including disabled

# Create a service unit
sudo cat > /etc/systemd/system/myapp.service << 'EOF'
[Unit]
Description=My Application
After=network.target postgresql.service
Wants=postgresql.service

[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/opt/myapp
EnvironmentFile=/opt/myapp/.env
ExecStart=/opt/myapp/bin/server
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StartLimitBurst=5
StartLimitIntervalSec=60

# Security hardening
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/myapp/data

[Install]
WantedBy=multi-user.target
EOF

# After creating/modifying service file
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp

# Debug failing service
sudo systemctl status myapp -l   # Full log output
journalctl -xe -u myapp          # Extended error info
systemd-analyze blame            # Startup time per service

Why

systemd is the standard init system on modern Linux. These commands cover 95% of service management tasks for deploying and operating applications.

Context

Linux server administration

Revisions (0)

No revisions yet.