【服务器】ubuntu 20 添加开机自启动

2022-09-01 13:49:51

开机自启动

ubuntu作为服务器使用时,常常需要在机器重启时能自动启动我们开发的服务。有时候我们想要脚本开机自动运行,那么就需要设置开机自启动脚本。网上有很多种解决方案,基本上是分为三种:

修改/etc/r.local

我在ubuntu18和ubuntu20.10都亲测 /etc/rc.d/rc.local开机启动脚本不生效。主要有以下步骤:

查看是否有/etc/rc.d/rc.local

ls -l /etc/rc.d/rc.local

我这边20这个版本的话,都没有这个文件。那就不管这个方式了

/lib/systemd/system增加开机启动服务

通常在网上现有的方法,主要是通过修改/etc/init.d,最后修改权限生成。但 Ubuntu 18.04 不再使用initd管理系统,改用systemd,包括用systemctl命令来替换了service和chkconfig的功能。systemd 默认读取 /etc/systemd/system 下的配置文件,该目录下的文件会链接/lib/systemd/system/下的文件。不同于以往的版本,ubuntu18.04默认不带/etc/rc.local文件,我们需要通过配置来让service生效。

检查系统目录/lib/systemd/system/test.service

如果没有自己新建,文件内容为(如果文件存在本身是没有[Install]项的,需要自己添加进去)

vim /lib/systemd/system/test.service# 编写内容[Unit]Description=testRequires=network-online.target#若需要联网后启动的话,则需要加入该参数After=network-online.target#若需要联网后启动的话,则需要加入该参数[Service]Type=forkingExecStart=/bin/bash /home/test/test.sh#执行的内容是脚本test.sh中的内容,其中包括它的绝对地址[Install]WantedBy=multi-user.target

此处可以自行增加一个service在该路径下,根据该路径下的格式,自行定制即可。详细参数信息可以见下Systemd 添加自定义服务(开机自启动).

修改配置文件后需要重加载配置

sudo systemctl daemon-reload

创建test.sh

vim /home/test/test.sh# 写入如下内容#!/bin/bashecho`date`,"ok">>/tmp/test.log

赋予可执行权限

chmod +x /home/test/test.sh

设置开机启动

systemctlenable test.service

查看启动的状态

systemctl status test.service
root@rex:/home/rex# systemctl status test.service
● test.service -test
   Loaded: loaded(/lib/systemd/system/test.service; enabled; vendor preset: enabled)
   Active: inactive(dead) since Sat2021-12-11 08:46:19 UTC; 35s ago
  Process:967ExecStart=/bin/bash /home/test/test.sh#执行的内容是脚本test.sh中的内容,其中包括它的绝对地址 (code=exited, status=0/SUCCESS)

Dec11 08:46:19 rex systemd[1]: Starting test...
Dec11 08:46:19 rex systemd[1]: Started test.# 查看文件是否写入
root@rex:/tmp# cat test.log
Sat Dec11 08:46:19 UTC2021,ok

关闭开机启动

systemctl disable test.service# 输出
root@rex:/tmp# systemctl disable test.service
Removed /etc/systemd/system/multi-user.target.wants/test.service.

update-rc.d增加开机启动服务

该方法主要是适用于/etc/init.d的服务的情况,现今低版本的linux主要是用它。现阶段不在赘述。下面给到链接。仅供参考。

https://m.linuxidc.com/Linux/2017-09/147178.htm.
https://www.cnblogs.com/yehui/p/9874866.html.

  • 作者:时光不等仁
  • 原文链接:https://blog.csdn.net/timewaitfornoone/article/details/121876412
    更新时间:2022-09-01 13:49:51