systemd-services

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Systemd Services

Systemd服务

Create, manage, and monitor systemd services and timers. Covers unit file authoring, dependency management, socket activation, resource limits, journalctl log analysis, and production hardening.
创建、管理和监控systemd服务与定时器。内容涵盖单元文件编写、依赖管理、套接字激活、资源限制、journalctl日志分析以及生产环境加固。

When to Use

使用场景

  • Deploying an application as a managed background service
  • Replacing cron jobs with systemd timers for better logging and dependency control
  • Setting up socket activation for on-demand service startup
  • Configuring resource limits (CPU, memory, I/O) for services
  • Debugging service startup failures and runtime crashes
  • Managing service dependencies and ordering
  • 将应用部署为受管理的后台服务
  • 使用systemd定时器替代cron任务,以实现更优的日志记录和依赖控制
  • 配置套接字激活,实现服务按需启动
  • 为服务配置资源限制(CPU、内存、I/O)
  • 调试服务启动失败和运行时崩溃问题
  • 管理服务依赖项与启动顺序

Prerequisites

前提条件

  • Linux system running systemd (most modern distributions)
  • Root or sudo access for creating system-level unit files
  • Application binary or script to run as a service
  • Understanding of the application's start/stop lifecycle
  • 运行systemd的Linux系统(大多数现代发行版均支持)
  • 创建系统级单元文件所需的Root或sudo权限
  • 可作为服务运行的应用程序二进制文件或脚本
  • 了解应用程序的启动/停止生命周期

Service Unit File -- Complete Example

服务单元文件——完整示例

ini
undefined
ini
undefined

/etc/systemd/system/myapp.service

/etc/systemd/system/myapp.service

[Unit] Description=MyApp Production Server Documentation=https://docs.example.com/myapp After=network-online.target postgresql.service Wants=network-online.target Requires=postgresql.service
[Service] Type=notify User=myapp Group=myapp WorkingDirectory=/opt/myapp
[Unit] Description=MyApp Production Server Documentation=https://docs.example.com/myapp After=network-online.target postgresql.service Wants=network-online.target Requires=postgresql.service
[Service] Type=notify User=myapp Group=myapp WorkingDirectory=/opt/myapp

Environment configuration

Environment configuration

EnvironmentFile=/etc/myapp/env Environment=NODE_ENV=production Environment=PORT=8080
EnvironmentFile=/etc/myapp/env Environment=NODE_ENV=production Environment=PORT=8080

Execution

Execution

ExecStartPre=/opt/myapp/bin/migrate --check ExecStart=/opt/myapp/bin/server --config /etc/myapp/config.yaml ExecStartPost=/opt/myapp/bin/healthcheck.sh ExecReload=/bin/kill -HUP $MAINPID ExecStop=/opt/myapp/bin/graceful-stop.sh
ExecStartPre=/opt/myapp/bin/migrate --check ExecStart=/opt/myapp/bin/server --config /etc/myapp/config.yaml ExecStartPost=/opt/myapp/bin/healthcheck.sh ExecReload=/bin/kill -HUP $MAINPID ExecStop=/opt/myapp/bin/graceful-stop.sh

Restart behavior

Restart behavior

Restart=on-failure RestartSec=5 StartLimitIntervalSec=300 StartLimitBurst=5
Restart=on-failure RestartSec=5 StartLimitIntervalSec=300 StartLimitBurst=5

Timeouts

Timeouts

TimeoutStartSec=30 TimeoutStopSec=30 WatchdogSec=60
TimeoutStartSec=30 TimeoutStopSec=30 WatchdogSec=60

Security hardening

Security hardening

NoNewPrivileges=true ProtectSystem=strict ProtectHome=true PrivateTmp=true ReadWritePaths=/var/lib/myapp /var/log/myapp CapabilityBoundingSet= AmbientCapabilities=
NoNewPrivileges=true ProtectSystem=strict ProtectHome=true PrivateTmp=true ReadWritePaths=/var/lib/myapp /var/log/myapp CapabilityBoundingSet= AmbientCapabilities=

Logging

Logging

StandardOutput=journal StandardError=journal SyslogIdentifier=myapp
[Install] WantedBy=multi-user.target
undefined
StandardOutput=journal StandardError=journal SyslogIdentifier=myapp
[Install] WantedBy=multi-user.target
undefined

Service Management Commands

服务管理命令

bash
undefined
bash
undefined

Reload systemd after creating or modifying unit files

Reload systemd after creating or modifying unit files

systemctl daemon-reload
systemctl daemon-reload

Start, stop, restart a service

Start, stop, restart a service

systemctl start myapp systemctl stop myapp systemctl restart myapp
systemctl start myapp systemctl stop myapp systemctl restart myapp

Reload service configuration without restart (if supported)

Reload service configuration without restart (if supported)

systemctl reload myapp
systemctl reload myapp

Enable service to start on boot

Enable service to start on boot

systemctl enable myapp
systemctl enable myapp

Enable and start in one command

Enable and start in one command

systemctl enable --now myapp
systemctl enable --now myapp

Disable and stop

Disable and stop

systemctl disable --now myapp
systemctl disable --now myapp

Check service status

Check service status

systemctl status myapp
systemctl status myapp

Check if a service is active, enabled, or failed

Check if a service is active, enabled, or failed

systemctl is-active myapp systemctl is-enabled myapp systemctl is-failed myapp
systemctl is-active myapp systemctl is-enabled myapp systemctl is-failed myapp

List all running services

List all running services

systemctl list-units --type=service --state=running
systemctl list-units --type=service --state=running

List all failed services

List all failed services

systemctl list-units --type=service --state=failed
systemctl list-units --type=service --state=failed

Show all properties of a service

Show all properties of a service

systemctl show myapp
systemctl show myapp

Show specific property values

Show specific property values

systemctl show myapp -p MainPID,MemoryCurrent,CPUUsageNSec
systemctl show myapp -p MainPID,MemoryCurrent,CPUUsageNSec

Mask a service (prevent it from being started at all)

Mask a service (prevent it from being started at all)

systemctl mask myapp
systemctl mask myapp

Unmask

Unmask

systemctl unmask myapp
systemctl unmask myapp

Reset a failed service state

Reset a failed service state

systemctl reset-failed myapp
undefined
systemctl reset-failed myapp
undefined

Timer Units (Cron Replacement)

定时器单元(替代Cron)

Timer File

定时器文件

ini
undefined
ini
undefined

/etc/systemd/system/backup.timer

/etc/systemd/system/backup.timer

[Unit] Description=Daily backup timer
[Timer]
[Unit] Description=Daily backup timer
[Timer]

Run daily at 2:30 AM

Run daily at 2:30 AM

OnCalendar=--* 02:30:00
OnCalendar=--* 02:30:00

If the system was off at the scheduled time, run when it boots

If the system was off at the scheduled time, run when it boots

Persistent=true
Persistent=true

Add random delay up to 15 minutes to avoid thundering herd

Add random delay up to 15 minutes to avoid thundering herd

RandomizedDelaySec=900
RandomizedDelaySec=900

Associate with a specific service (defaults to same name .service)

Associate with a specific service (defaults to same name .service)

Unit=backup.service
[Install] WantedBy=timers.target
undefined
Unit=backup.service
[Install] WantedBy=timers.target
undefined

Corresponding Service File

对应的服务文件

ini
undefined
ini
undefined

/etc/systemd/system/backup.service

/etc/systemd/system/backup.service

[Unit] Description=Daily backup job After=network-online.target Wants=network-online.target
[Service] Type=oneshot User=backup ExecStart=/usr/local/bin/run-backup.sh StandardOutput=journal StandardError=journal
undefined
[Unit] Description=Daily backup job After=network-online.target Wants=network-online.target
[Service] Type=oneshot User=backup ExecStart=/usr/local/bin/run-backup.sh StandardOutput=journal StandardError=journal
undefined

Timer Management

定时器管理

bash
undefined
bash
undefined

Common OnCalendar expressions:

Common OnCalendar expressions:

minutely, hourly, daily, weekly, monthly

minutely, hourly, daily, weekly, monthly

--* 06:00:00 Daily at 6 AM

--* 06:00:00 Daily at 6 AM

Mon..Fri --* 09:00 Weekdays at 9 AM

Mon..Fri --* 09:00 Weekdays at 9 AM

*:0/15 Every 15 minutes

*:0/15 Every 15 minutes

Validate calendar expressions

Validate calendar expressions

systemd-analyze calendar "Mon..Fri --* 09:00"
systemd-analyze calendar "Mon..Fri --* 09:00"

List all active timers

List all active timers

systemctl list-timers --all
systemctl list-timers --all

Enable and start a timer

Enable and start a timer

systemctl enable --now backup.timer
systemctl enable --now backup.timer

Run the associated service immediately (for testing)

Run the associated service immediately (for testing)

systemctl start backup.service
undefined
systemctl start backup.service
undefined

Socket Activation

套接字激活

ini
undefined
ini
undefined

/etc/systemd/system/myapp.socket

/etc/systemd/system/myapp.socket

[Unit] Description=MyApp Socket
[Socket] ListenStream=8080 Accept=no
[Unit] Description=MyApp Socket
[Socket] ListenStream=8080 Accept=no

Optionally bind to a specific IP

Optionally bind to a specific IP

ListenStream=10.0.1.10:8080

ListenStream=10.0.1.10:8080

[Install] WantedBy=sockets.target

```ini
[Install] WantedBy=sockets.target

```ini

/etc/systemd/system/myapp.service

/etc/systemd/system/myapp.service

[Unit] Description=MyApp Server Requires=myapp.socket
[Service] Type=notify User=myapp ExecStart=/opt/myapp/bin/server
[Unit] Description=MyApp Server Requires=myapp.socket
[Service] Type=notify User=myapp ExecStart=/opt/myapp/bin/server

Service receives the socket file descriptor from systemd

Service receives the socket file descriptor from systemd

[Install] WantedBy=multi-user.target

```bash
[Install] WantedBy=multi-user.target

```bash

Enable the socket (service starts on first connection)

Enable the socket (service starts on first connection)

systemctl enable --now myapp.socket
systemctl enable --now myapp.socket

Check socket status

Check socket status

systemctl status myapp.socket
systemctl status myapp.socket

List all listening sockets

List all listening sockets

systemctl list-sockets
undefined
systemctl list-sockets
undefined

Dependency Management

依赖管理

bash
undefined
bash
undefined

Key [Unit] directives for ordering and dependencies:

Key [Unit] directives for ordering and dependencies:

After= Start after these units (ordering only)

After= Start after these units (ordering only)

Requires= Hard dependency -- fail if this unit cannot start

Requires= Hard dependency -- fail if this unit cannot start

Wants= Soft dependency -- try to start, don't fail if unavailable

Wants= Soft dependency -- try to start, don't fail if unavailable

PartOf= Stop this unit when the parent stops

PartOf= Stop this unit when the parent stops

Conflicts= Cannot run alongside this unit

Conflicts= Cannot run alongside this unit

Visualize the dependency tree for a service

Visualize the dependency tree for a service

systemctl list-dependencies myapp
systemctl list-dependencies myapp

Show reverse dependencies (who depends on this unit)

Show reverse dependencies (who depends on this unit)

systemctl list-dependencies myapp --reverse
systemctl list-dependencies myapp --reverse

Analyze boot order for a service

Analyze boot order for a service

systemd-analyze critical-chain myapp.service
undefined
systemd-analyze critical-chain myapp.service
undefined

Resource Limits (cgroups v2)

资源限制(cgroups v2)

ini
undefined
ini
undefined

/etc/systemd/system/myapp.service.d/limits.conf

/etc/systemd/system/myapp.service.d/limits.conf

(drop-in override file)

(drop-in override file)

[Service]
[Service]

Memory limits

Memory limits

MemoryMax=1G MemoryHigh=768M
MemoryMax=1G MemoryHigh=768M

CPU limits

CPU limits

CPUQuota=200% # Up to 2 full CPU cores CPUWeight=100 # Relative weight (default=100)
CPUQuota=200% # Up to 2 full CPU cores CPUWeight=100 # Relative weight (default=100)

I/O limits

I/O limits

IOWeight=50 IOReadBandwidthMax=/dev/sda 100M IOWriteBandwidthMax=/dev/sda 50M
IOWeight=50 IOReadBandwidthMax=/dev/sda 100M IOWriteBandwidthMax=/dev/sda 50M

Process limits

Process limits

LimitNOFILE=65535 LimitNPROC=4096 TasksMax=512
LimitNOFILE=65535 LimitNPROC=4096 TasksMax=512

Disable OOM killer (let the app handle it)

Disable OOM killer (let the app handle it)

OOMPolicy=continue

```bash
OOMPolicy=continue

```bash

Apply drop-in overrides without editing the main unit file

Apply drop-in overrides without editing the main unit file

mkdir -p /etc/systemd/system/myapp.service.d/
cat <<'EOF' > /etc/systemd/system/myapp.service.d/limits.conf [Service] MemoryMax=1G CPUQuota=200% EOF
systemctl daemon-reload systemctl restart myapp
mkdir -p /etc/systemd/system/myapp.service.d/
cat <<'EOF' > /etc/systemd/system/myapp.service.d/limits.conf [Service] MemoryMax=1G CPUQuota=200% EOF
systemctl daemon-reload systemctl restart myapp

View current resource usage for a service

View current resource usage for a service

systemctl status myapp # Shows Memory and CPU systemd-cgtop # Real-time cgroup resource usage
systemctl status myapp # Shows Memory and CPU systemd-cgtop # Real-time cgroup resource usage

Edit a service's overrides interactively

Edit a service's overrides interactively

systemctl edit myapp
systemctl edit myapp

This creates a drop-in file automatically

This creates a drop-in file automatically

undefined
undefined

Journalctl Log Analysis

Journalctl日志分析

bash
undefined
bash
undefined

Follow logs for a service in real time

Follow logs for a service in real time

journalctl -u myapp -f
journalctl -u myapp -f

Show logs since last boot

Show logs since last boot

journalctl -u myapp -b
journalctl -u myapp -b

Show logs for a specific time range

Show logs for a specific time range

journalctl -u myapp --since "2025-01-15 08:00" --until "2025-01-15 12:00"
journalctl -u myapp --since "2025-01-15 08:00" --until "2025-01-15 12:00"

Show only error and above

Show only error and above

journalctl -u myapp -p err
journalctl -u myapp -p err

Show the last 100 lines with full messages (no truncation)

Show the last 100 lines with full messages (no truncation)

journalctl -u myapp -n 100 --no-pager -l
journalctl -u myapp -n 100 --no-pager -l

Show logs in JSON format (for parsing)

Show logs in JSON format (for parsing)

journalctl -u myapp -o json-pretty --no-pager | head -50
journalctl -u myapp -o json-pretty --no-pager | head -50

Check journal disk usage and vacuum old entries

Check journal disk usage and vacuum old entries

journalctl --disk-usage journalctl --rotate journalctl --vacuum-time=7d journalctl --vacuum-size=500M
undefined
journalctl --disk-usage journalctl --rotate journalctl --vacuum-time=7d journalctl --vacuum-size=500M
undefined

Troubleshooting

故障排查

SymptomDiagnostic CommandCommon Fix
Service fails to start
systemctl status myapp
,
journalctl -u myapp -n 50
Check ExecStart path, permissions, config syntax
Service keeps restarting
journalctl -u myapp --since "5 min ago"
Check StartLimitBurst; look for crash in logs
"Main process exited, code=exited, status=217"
journalctl -u myapp
User or group in unit file does not exist
"Failed to set up mount namespacing"Check ProtectSystem/PrivateTmpKernel too old or SELinux blocking; relax directives
Timer not firing
systemctl list-timers
,
systemctl status backup.timer
Ensure timer is enabled; validate OnCalendar expression
Service starts before dependencyCheck After= and Requires=Add
After=dependency.service
for ordering
OOM killed
journalctl -k | grep oom
,
dmesg
Increase MemoryMax or optimize application memory
Cannot bind to port 80Check AmbientCapabilitiesAdd
CAP_NET_BIND_SERVICE
or use a higher port
症状诊断命令常见修复方案
服务无法启动
systemctl status myapp
,
journalctl -u myapp -n 50
检查ExecStart路径、权限、配置语法
服务持续重启
journalctl -u myapp --since "5 min ago"
检查StartLimitBurst;查看日志中的崩溃信息
"Main process exited, code=exited, status=217"
journalctl -u myapp
单元文件中指定的用户或组不存在
"Failed to set up mount namespacing"检查ProtectSystem/PrivateTmp内核版本过旧或SELinux拦截;放宽相关配置项
定时器未触发
systemctl list-timers
,
systemctl status backup.timer
确保定时器已启用;验证OnCalendar表达式
服务在依赖项启动前启动检查After=和Requires=添加
After=dependency.service
以调整启动顺序
被OOM killer终止
journalctl -k | grep oom
,
dmesg
增大MemoryMax或优化应用内存占用
无法绑定到80端口检查AmbientCapabilities添加
CAP_NET_BIND_SERVICE
或使用更高端口

Related Skills

相关技能

  • linux-administration
    -- General system administration context
  • performance-tuning
    -- Kernel tuning and resource optimization
  • user-management
    -- Service accounts and permissions
  • backup-recovery
    -- Scheduling backups with systemd timers
  • linux-administration
    -- 通用系统管理场景
  • performance-tuning
    -- 内核调优与资源优化
  • user-management
    -- 服务账户与权限管理
  • backup-recovery
    -- 使用systemd定时器调度备份任务