1.在 /etc/systemd/system/ 目录下创建一个新的服务文件,命名为 your_service_name.service。例如,如果你的进程是一个 Python 脚本, 可以创建 my_python_script.service。
sudo nano /etc/systemd/system/my_python_script.service
2.编写服务文件:
在服务文件中,定义服务的描述、执行的命令和其他参数。以下是一个示例服务文件的内容:
[Unit]
Description=My Python Script Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /path/to/your_script.py
Restart=always
User=nobody
Group=nogroup
[Install]
WantedBy=multi-user.target
其中:
3.重新加载 systemd 配置:
创建或修改服务文件后,需要重新加载 systemd 配置以使其生效。
sudo systemctl daemon-reload
4.启动和启用服务:
启动服务并设置为开机自启。
sudo systemctl start my_python_script.service
sudo systemctl enable my_python_script.service
5.检查服务状态:
可以检查服务的状态以确认其是否正常运行。
sudo systemctl status my_python_script.service
如果一切配置正确,systemctl 将管理你的进程,并根据你的配置进行启动、停止和重启操作。
sudo systemctl stop my_python_script.service
sudo systemctl restart my_python_script.service
在 systemd 服务单元文件中,可以使用许多参数来配置服务的行为。以下是一些常用和重要的参数:
[Unit]
# 服务的描述
Description=My Example Service
# 服务的文档链接
Documentation=https://example.com/docs
# 服务所依赖的其他单元,如果这些单元没有运行,则当前单元也不会启动
Requires=network.target
# 在指定单元之后启动
After=network.target
[Service]
# 服务的启动类型
Type=simple
# 启动服务的命令
ExecStart=/usr/bin/python3 /path/to/your_script.py
# 在 ExecStart 之前运行的命令
ExecStartPre=/bin/echo "Starting service"
# 在 ExecStart 之后运行的命令
ExecStartPost=/bin/echo "Service started"
# 停止服务的命令
ExecStop=/bin/echo "Stopping service"
# 重载服务的命令
ExecReload=/bin/kill -HUP $MAINPID
# 重启服务的条件,这里表示服务停止后总是重启
Restart=always
# 在重新启动服务之前的等待时间
RestartSec=5
# 运行服务的用户
User=nobody
# 运行服务的用户组
Group=nogroup
# 服务的工作目录
WorkingDirectory=/path/to/working_directory
# 设置环境变量
Environment="VAR1=value1 VAR2=value2"
# 包含环境变量的文件
EnvironmentFile=/path/to/envfile
# 指定服务的 PID 文件
PIDFile=/run/my_service.pid
# 服务启动的超时时间
TimeoutStartSec=30
# 服务停止的超时时间
TimeoutStopSec=30
# 设置文件描述符的限制
LimitNOFILE=4096
# 设置进程数的限制
LimitNPROC=512
[Install]
# 指定服务在多用户模式下启动
WantedBy=multi-user.target
# 为当前单元提供别名
Alias=my_service_alias