linux开机自动启动
本文介绍linux服务的开户自动启动方式,分两两种,以下
使用 systemctl 方式
在 /lib/systemd/system/ 目录创建文件,并写以下内容
1[Unit]
2Description=liquid api server Compatibility
3After=network.target
4
5[Service]
6User=go
7ExecStart=/data/subfile/liquid-api-server/liquid-api
8#ExecStartPre=rm -rf /data/subfile/tmp/cache/*
9#ExecStartPost=
10Restart=on-failure
11RestartSec=5s
12SysVStartPriority=99
13
14[Install]
15WantedBy=multi-user.target
注解
[Unit] 区块,启动顺序与依赖关系
Description 服务注释,可随意写
After 指定在某个服务启动以后,再启动此服务,比如这个是依赖网络的,那就在网络服务启动之再启动这个
[Service] 区块是核心,主要在这里
User 指定运行程序的用户,或不指定,则是root用户
ExecStart 指定运行的程序路径和参数,注意:这里必须是绝对路径
ExecStartPre 指定运行程序前的指令,比如每次启动前清除缓存
ExecStartPost 启动后的执行后的指令
Restart 指定重启行为,on-failure 代表非正常退出时重启(退出代码非0)
RestartSec 退出后重启的间隔
SysVStartPriority 优先级,自定服务一般设置为99即可
[install] 区块保持默认即可
使用 启动脚本方式
1 /data/subfile/liquid-api-server/liquid-api
22019/12/07 10:11:07 configFile.Get err
3#open config/app-local.yaml: no such file or directory
如上日志,目前咱们这个服务,没办法使用绝对路径来启动,必须先cd到目录,才可以启动,所以只能用这种方法
ubuntu 18.04 以后,默认没有开户 /etc/rc.local 开机启动脚本,首先开启它
修改 /lib/systemd/system/rc-local.service 文件,内容保持和下方一样即可
1[Unit]
2Description=/etc/rc.local Compatibility
3Documentation=man:systemd-rc-local-generator(8)
4#ConditionFileIsExecutable=/etc/rc.local
5After=network.target
6
7[Service]
8Type=forking
9ExecStart=/etc/rc.local start
10TimeoutSec=0
11RemainAfterExit=yes
12GuessMainPID=no
13SysVStartPriority=99
14
15[Install]
16WantedBy=multi-user.target
创建 /etc/rc.local 文件
1sudo touch /etc/rc.local
2
3sudo chmod +x /etc/rc.local
启用 rc.local 脚本
1systemctl enable rc-local.service
创建启动脚本,并添加自起服务
1sudo vim /usr/share/subtitle.sh
脚本位置无所谓,记住就好,后面会用到
文件添加以下内容,咱们这个因为必须 cd到目录才可以启动,并且指定 go 用户运行,所以脚本如下,其它的参考示例了。
1#!/bin/bash
2sleep 10
3cd /data/subfile/liquid-api-server
4sudo -u go nohup /data/subfile/liquid-api-server/liquid-api > /dev/null 2>&1 &
5sleep 1
6cd /data/subfile/subtitle-server
7sudo -u go nohup /data/subfile/subtitle-server/subtitle > /dev/null 2>&1 &
这个启用了 nohup来保证不会因为shell的断开而停止后台运行, > /dev/null 2>&1 & 表示将程序所产生的所有输出(不论标准或错误),全部重定向到 /dev/null ,并且后台运行, 默认情况下,nohup 会在执行的目录创建.nohup来记录程序的标准输出和错误输出,而有些程序的标准输出量特别多,时间长了,会把磁盘空间占满,所以重写向到垃圾桶,可保证不会因为程序的输出信息而占满磁盘空间带来其它的问题。
添加执行权限
1sudo chmod +x /usr/share/subtitle.sh
添加到 /etc/rc.local
1sudo vim /etc/rc.local
添加e脚本的问题,注意脚本需要有执行位权限:
1#!/bin/sh -e
2
3/usr/share/subtitle.sh
4
5eixt 0
以后所有添加的其它服务,都必须添加在 exit 0 这一行的前面