以下是在 Debian 上使用 systemd 设置 sing-box 开机自启的步骤:

1. 创建 systemd 服务单元文件:

您需要创建一个 .service 文件来定义如何运行 sing-box。通常将这些文件放在 /etc/systemd/system/ 目录下。

使用文本编辑器(如 nanovim)创建名为 sing-box.service 的文件:

1
/etc/systemd/system/sing-box.service

将以下内容粘贴到文件中。您需要根据您的实际情况修改 User, WorkingDirectory, 和 ExecStart 的路径:

1
2
3
4
5
6
7
8
9
10
11
12
[Unit]
Description=Sing-box Proxy Service
After=network.target

[Service]
User=your_username # 将 "your_username" 替换为运行 sing-box 的用户名
WorkingDirectory=/path/to/sing-box/directory # 将 "/path/to/sing-box/directory" 替换为 sing-box 可执行文件所在的目录
ExecStart=/path/to/sing-box -c /path/to/config.json # 将 "/path/to/sing-box" 替换为 sing-box 可执行文件的完整路径,将 "/path/to/config.json" 替换为您的配置文件路径
Restart=on-failure

[Install]
WantedBy=multi-user.target

解释一下这些字段:

  • [Unit] 部分:
    • Description: 服务的描述信息。
    • After=network.target: 指明 sing-box.service 应该在网络服务启动后启动。
  • [Service] 部分:
    • User: 指定运行 sing-box 进程的用户。建议使用非 root 用户以提高安全性。
    • WorkingDirectory: 指定 sing-box 进程的工作目录。
    • ExecStart: 指定启动 sing-box 的命令。-c 参数通常用于指定配置文件的路径。请确保使用 sing-box 可执行文件的完整路径。
    • Restart=on-failure: 配置在 sing-box 进程因错误而退出时自动重启。您可以根据需要选择其他重启策略(例如 on-success, always 等)。
  • [Install] 部分:
    • WantedBy=multi-user.target: 指明该服务应该在多用户系统启动级别下启用(通常是正常操作的级别)。

2. 保存并关闭文件:

如果您使用的是 nano,请按 Ctrl+X,然后按 Y 确认保存,最后按回车退出。

3. 启用并启动 sing-box 服务:

现在,您需要告诉 systemd 在启动时启用这个服务,并立即启动它。

  • 启用服务 (设置开机自启):

    1
    systemctl enable sing-box.service
  • 立即启动服务:

    1
    systemctl start sing-box.service

4. 检查服务状态:

您可以使用以下命令来检查 sing-box 服务的运行状态,以确保它已成功启动并且没有错误:

1
systemctl status sing-box.service

查看输出中的 Active: 行,如果显示 active (running),则表示服务已成功启动。如果有错误,请仔细阅读输出以获取更多信息。

5. (可选)停止和禁用服务:

如果您需要停止或禁用开机自启,可以使用以下命令:

  • 停止服务:

    1
    systemctl stop sing-box.service
  • 禁用开机自启:

    1
    systemctl disable sing-box.service

重要注意事项:

  • 替换占位符: 务必将 your_username, /path/to/sing-box/directory, /path/to/sing-box, 和 /path/to/config.json 替换为您的实际路径和用户名。
  • 日志记录: 如果您需要更详细的日志信息,可以考虑在 [Service] 部分添加 StandardOutput=append:/var/log/sing-box.logStandardError=append:/var/log/sing-box.log 来将输出和错误追加到日志文件中。您可能还需要创建 /var/log/sing-box.log 文件并设置适当的权限。
  • 配置文件权限: 确保运行 sing-box 的用户对配置文件具有读取权限。
  • 网络依赖: 如果 sing-box 依赖于特定的网络接口或服务完全启动后才能正常工作,您可以更细致地调整 After= 指令。

按照这些步骤,您应该能够在 Debian 系统上成功设置 sing-box 开机自启。