Linux 下使用 systemctl 配置服务开机自启动

在Linux系统中,使用 systemctl 配置服务开机自启动是推荐的方式,可实现程序崩溃后自动重启,且配置过程标准化。

1、创建 service 文件

在 /etc/systemd/system/ 目录下新建 .service 文件(如myapp.service),示例如下:

[Unit]
Description=My Custom Application
After=network.target  # 指定依赖,确保网络就绪后再启动服务

[Service]
Type=simple           # 常用类型:simple(前台运行)/forking(后台守护进程)
WorkingDirectory=/path/to/    # 设置工作目录(可选),程序的相对路径会基于此目录
User=root           # 运行用户(可选)
ExecStart=/path/to/myapp --arg1 value1  # 启动命令(绝对路径)
# ExecStart=/bin/bash /path/to/script.sh  # 需确保脚本有执行权限(chmod +x /path/to/script.sh)
Restart=always        # 崩溃后自动重启(除systemctl stop外)
RestartSec=5          # 重启间隔(秒),崩溃后等待5秒再重启,避免频繁重启
Environment="VAR=value"  # 环境变量(可选)

[Install]
WantedBy=multi-user.target  # 多用户模式启动

2、启动服务并验证

sudo systemctl daemon-reload  # 重新加载systemd配置,修改.service文件后必须执行
sudo systemctl enable myapp.service   # 启用开机自启
sudo systemctl disable myapp.service  # 禁用开机自启
sudo systemctl start myapp.service  # 启动服务
sudo systemctl stop myapp.service   # 停止服务
sudo systemctl status myapp.service # 查看服务状态
sudo systemctl restart myapp.service  # 重启
sudo journalctl -u myapp.service -f # 实时查看服务日志

3、示例

[Unit]
Description=wsService
After=network.target

[Service]
Type=simple
WorkingDirectory=/root/ws/
ExecStart=/bin/bash /root/ws/start42.sh
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target