传统的 SysVinit 缺乏对子进程 Cgroups 级的监控与限制。编写带有安全沙箱与自动化重启策略的 Systemd 服务单元是保障服务常驻的关键。
一、 高阶硬化 Unit 配置文件 (/etc/systemd/system/app.service)
[Unit] Description=Production Application Service After=network-online.target sysmaint.target Wants=network-online.target Documentation=https://xiaowan.uk/docs/app [Service] Type=notify User=www-data Group=www-data WorkingDirectory=/opt/app ExecStart=/opt/app/bin/app-server --config /etc/app/config.yaml ExecReload=/bin/kill -s HUP $MAINPID # 进程崩溃保护与限频 Restart=on-failure RestartSec=3s StartLimitIntervalSec=60s StartLimitBurst=3 # 资源硬性隔离 (Cgroups) CPUWeight=100 MemoryMax=2G MemoryHigh=1.8G LimitNOFILE=65535 # 安全沙箱加固 ProtectSystem=strict ProtectHome=true ReadWritePaths=/opt/app/data /var/log/app PrivateTmp=true NoNewPrivileges=true [Install] WantedBy=multi-user.target