开机启动方法


在Ubuntu系统中配置开机自启动脚本可通过以下方法实现:

1. 使用systemd服务

在/etc/systemd/system/下创建.service文件(如:rc-local.service),内容示

[Unit]
Description=rc-local # 可自定义
Requires=network-online.target # 若需要联网后启动的话,则需要加入该参数
After=network-online.target # 若需要联网后启动的话,则需要加入该参数

[Service]
Type=forking
Restart=always
RestartSec=1
ExecStart=/opt/rc-local.sh start # 这里写 rc-local.sh 文件的 绝对地址
ExecStop=/opt/rc-local.sh stop

[Install]
WantedBy=multi-user.target

通过systemd服务依赖关系控制 在.service文件中使用After和Wants/Requires字段定义启动顺序:

After=network.target serviceB.service #确保 network 和 serviceB 就绪后启动
Requires=serviceB.service # 强依赖(serviceB失败则自己不启动)

After:指定依赖项 Wants:弱依赖(不影响主服务状态) Requires:强依赖(依赖失败则服务终止)

2. Before: 使用字段反向控制

在服务文件中添加Before=serviceB.service,表示当前服务需在serviceB之前启动。

3. 创建rc-local.sh文件

sudo vim /opt/rc-local.sh

输入以下内容:

#!/bin/bash

# 自动检测并执行当前目录可执行文件
APP_FULLPATH=$(find . -maxdepth 1 -type f -executable | grep -v "\.sh$" | head -n 1)
# 应用名称
APP_NAME=$(basename $APP_FULLPATH)
PID_FILE="/var/log/${APP_NAME}.pid"
LOG_FILE="/var/log/${APP_NAME}.log"

# 检查进程是否存在
is_running() {
    [ -f "$PID_FILE" ] && ps -p $(cat "$PID_FILE") > /dev/null 2>&1
}

# 启动应用
start() {
    if is_running; then
        echo "$APP_NAME 已在运行 (PID: $(cat $PID_FILE))"
    else
        nohup "$APP_NAME" >> "$LOG_FILE" 2>&1 &
        echo $! > "$PID_FILE"
        echo "$APP_NAME 已启动 (PID: $(cat $PID_FILE))"
        tail -f "$LOG_FILE"
    fi
}

# 停止应用
stop() {
    if is_running; then
        PID=$(cat "$PID_FILE")
        kill $PID
        rm "$PID_FILE"
        echo "$APP_NAME 已停止"
    else
        echo "$APP_NAME 未运行"
    fi
}

# 重启应用
restart() {
    stop
    sleep 2
    start
}

# 查看状态
status() {
    if is_running; then
        echo "$APP_NAME 正在运行 (PID: $(cat $PID_FILE))"
    else
        echo "$APP_NAME 未运行"
    fi
}

# 主逻辑
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
    echo "用法: $0 {start|stop|restart|status}"
    exit 1
esac

4. 设置rc.local文件权限

sudo chmod +x /opt/rc-local.sh

5. 添加开机启动命令

sudo systemctl daemon-reload    # 重载配置文件
sudo systemctl enable rc-local  # 设置开机自启

6. 启用rc-local服务

sudo systemctl start rc-local   # 立即启动服务
sudo systemctl stop rc-local    # 停止

验证状态可使用systemctl is-enabled rc-local