不像其他linux一樣設置不成功原因
由於從ubuntu-16.10開始ubuntu不再使用initd管理系統,改用systemd
看了systemd的使用方法,發現改動有點大,包括包括用 systemctl 命令來替換了 service 和 chkconfig 的功能。
比如以前啓動 mysql 服務用:
sudo是管理權限,如果當前用戶是管理員請忽略。
sudo service mysql start
現在用:
sudo systemctl start mysqld.service
其實這個改動到不是算大,主要是開機啓動比以前複雜多了。systemd 默認讀取 /etc/systemd/system 下的配置文件,該目錄下的文件會鏈接/lib/systemd/system/下的文件。
執行 ls /lib/systemd/system 你可以看到有很多啓動腳本,其中就有我們需要的 rc.local.service
打開腳本內容:
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
一般正常的啓動文件主要分成三部分
[Unit] 段: 啓動順序與依賴關係
[Service] 段: 啓動行爲,如何啓動,啓動類型
[Install] 段: 定義如何安裝這個配置文件,即怎樣做到開機啓動
可以看出,/etc/rc.local 的啓動順序是在網絡後面,但是顯然它少了 Install 段,也就沒有定義如何做到開機啓動,所以顯然這樣配置是無效的。 因此我們就需要在後面幫他加上 [Install] 段:
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
這裏需要注意一下,ubuntu-18.04 默認是沒有 /etc/rc.local 這個文件的,需要自己創建
下面整體說明怎麼設置ubuntu-18.04開機啓動腳本
1.建立rc-local.service文件
sudo vi /etc/systemd/system/rc-local.service
2.將下列內容複製進rc-local.service文件
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
[Install]
WantedBy=multi-user.target
3.創建文件rc.local
sudo vi /etc/rc.local
4.將下列內容複製進rc.local文件
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo java -jar /home/intel/XXX.jar --spring.config.location=/home/intel/config/application.properties > /home/intel/XXXX.log & > /usr/local/test.log
exit 0
5.給rc.local加上權限
sudo chmod +x /etc/rc.local
6.啓用服務
sudo systemctl enable rc-loca
7.啓動服務並檢查狀態
sudo systemctl start rc-local.service
sudo systemctl status rc-local.service
8.重啓並檢查test.log文件
cat /usr/local/test.log