Linux 设置添加开机启动的几种方法

2024年5月7日服务器运维评论5,701字数 1674阅读5分34秒阅读模式

Ethan_2024-05-07_14-24-03

1、修改开机启动文件

这种方式已经比较古老了,并不推荐。

开机启动文件为:/etc/rc.local(或者/etc/rc.d/rc.local)

只需要在文件新添加行,填入服务的绝对路径即可。

Ethan_2024-05-07_12-19-03

注意还要修改rc.local 文件的执行权限:

chmod +x  /etc/rc.local

2、执行脚本放到启动脚本目录

将写好的脚本(.sh文件)放到目录 /etc/profile.d/下,系统启动后就会自动执行该目录下的所有shell脚本。

3、通过 systemctl 管理

可以自定义服务文件,添加到系统服务,通过 Systemctl 管理。

文件名类似:nginx.service

保存到目录:/usr/lib/systemd/system

就可以通过文件名来管理,包括开机启动,停止等。

注意服务文件有格式要求,类似这样:

[Unit]:
Description:描述服务
After:描述服务类别

[Service]服务运行参数的设置
Type=forking            是后台运行的形式
ExecStart               为服务的具体运行命令
ExecReload              为服务的重启命令
ExecStop                为服务的停止命令
PrivateTmp=True         表示给服务分配独立的临时空间
注意:启动、重启、停止命令全部要求使用绝对路径

[Install]               服务安装的相关设置,可设置为多用户
WantedBy=multi-user.target

可以去这个目录下去抄已经存在的文件,来改为自己的,不容易出错。

4、通过 chkconfig 命令设置

chkconfig 是一个在 Linux 系统中用于管理系统服务的命令行工具,主要用于控制服务的启动和停止以及设置服务的自启动状态。

先写好服务脚本文件,就可以使用chkconfig来管理这个服务了。

服务脚本通常位于 /etc/init.d/ 目录下,具有可执行权限,并且包含启动、停止、重启等功能。这个脚本通常以 Bash 脚本编写。

具体命令可以参考下面的官方提示:

# 官方帮助
usage:   chkconfig [--list] [--type <type>] [name]
         chkconfig --add <name>
         chkconfig --del <name>
         chkconfig --override <name>
         chkconfig [--level <levels>] [--type <type>] <name> <on|off|reset|resetpriorities>

例如我写好一个test_server.sh放到 /etc/rc.d/init.d下,

并修改其权限:chmod +x /etc/rc.d/init.d/test_server.sh

代码如下:

#!/bin/sh
#chkconfig: 35 20 80
#description: test server

# 启动服务
start() {
    echo "Starting my_service..."
    # 启动命令
}

# 停止服务
stop() {
    echo "Stopping my_service..."
    # 停止命令
}

# 重启服务
restart() {
    stop
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit 0

那么我就可以使用chkconfig --add test_service来添加这个服务。

现在我就可以开始设置开机启动,或者通过service命令来调用这个服务了。

[root@test_pc init.d]# pwd
>> /etc/rc.d/init.d
[root@test_pc init.d]# chkconfig test_service on
[root@test_pc init.d]# service test_service start
>> Starting my_service...
[root@test_pc init.d]# service test_service restart
>> Stopping my_service...
>> Starting my_service...

匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定