Systemd 使用
非 root 用户使用 Systemd
需要 root 用户执行下面的命令将用户的服务长驻
sudo loginctl enable-linger <username>
创建服务
mkdir ~/.config/systemd/user
cd ~/.config/systemd/user
vim test.service
service 文件
[Unit]
AssertPathExists=/home/ghost/ghost
[Service]
WorkingDirectory=/home/ghost/ghost
Environment=GHOST_NODE_VERSION_CHECK=false
ExecStart=/usr/bin/npm start --production
Restart=always
PrivateTmp=true
NoNewPrivileges=true
[Install]
WantedBy=default.target
常规操作
systemctl --user enable test.service
systemctl --user start test.service
systemctl --user status test.service
查看日志
journalctl -n -f -u test
# -n 表示 返回最新的日志
# -f 表示 持续显示最新的日志,类似 tail -f
# -u 表示只显示哪个service的日志
基础的 Service 文件
[Unit]
# 服务描述
Description=My Custom Server
# 确保网络就绪后启动
After=network.target
[Service]
# 主进程类型(simple/forking)
Type=simple
# 运行用户(建议非root)
User=appuser
# 运行组
Group=appgroup
# 工作目录
WorkingDirectory=/opt/app
# 启动命令(完整路径)
ExecStart=/opt/app/myserver
# 失败时自动重启
Restart=on-failure
# 重启间隔
RestartSec=5s
# 环境变量(可选)
Environment="KEY=value"
Environment="KEY1=value1"
# 日志配置(可选)
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myserver
[Install]
# 多用户模式下启用
WantedBy=multi-user.target
Read other posts