本文最后更新于 2025-09-20,文章内容可能已经过时。

Rocky Linux 9 配置开机服务

在Rocky Linux 9中,通过创建systemd服务单元文件来配置开机自启动服务。

配置开机服务

1. 创建服务文件

sudo vim /etc/systemd/system/test.service

2. 服务文件内容

[Unit]
Description=Test Application Service
After=network.target

[Service]
Type=forking
ExecStart=/root/test/start.sh
Restart=always
RestartSec=10
User=root
WorkingDirectory=/root/test

[Install]
WantedBy=multi-user.target

3. 启动脚本内容

#!/bin/bash
# 强制杀死8022端口占用
lsof -ti:8022 | xargs -r kill -9
# 后台执行main程序
cd /root/test
nohup ./main > /dev/null 2>&1 &

4. 设置权限

sudo chmod +x /root/test/start.sh
sudo chmod 644 /etc/systemd/system/test.service

5. 启用服务

sudo systemctl daemon-reload
sudo systemctl enable test.service
sudo systemctl start test.service

验证配置

sudo systemctl status test.service
sudo systemctl is-enabled test.service

服务管理

# 启动服务
sudo systemctl start test.service

# 停止服务
sudo systemctl stop test.service

# 重启服务
sudo systemctl restart test.service

# 禁用开机自启
sudo systemctl disable test.service

故障排除

# 查看服务日志
sudo journalctl -u test.service -f

# 重新加载配置
sudo systemctl daemon-reload

总结

本教程介绍了在Rocky Linux 9中通过systemd创建开机自启动服务的方法。

配置步骤

  1. 创建/etc/systemd/system/test.service文件
  2. 编写启动脚本并设置权限
  3. 启用并启动服务

适用于Rocky Linux 9系统