开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情
前言
-
此方法乃是作者亲自实践操作所得,亲测有效
-
适用的 Linux 版本为 CentOS7.0,其他版本不清楚是否可用
-
查看 Linux 服务器版本的命令为:
lsb_release -a
操作步骤
- 新建启动jar包的sh文件
nohup java -jar XXX.jar >/dev/null 2>&1 &
用你的项目名称代替上述的XXX
此 sh 文件,命名为 startup.sh
-
设置自启动命令
在你的linux中执行命令:
cd /etc/rc.d进入rc.d目录执行命令:
cat rc.local查看文件内容
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
上述代码为 rc.local 文件中自有内容,不需要改动
- 修改rc.local
执行命令:vi rc.local
然后按下键盘上的【i】键进入修改模式
接着在代码尾部添加代码:
cd /myApp/test
sh /myApp/test/startup.sh
第一句为进入你项目所在的目录,我这里把项目放在/myApp/test下 第二句执行该目录下的sh文件
说明:
如果不提前进入所在目录,直接执行第二句,也会开机自启动,但是日志文件会在根目录下的 log 文件中。只有先进入,再执行,项目的日志文件才会在 test 文件夹下
test 文件中有 jar 包、startup.sh、以及 jar 包的日志文件 logs
然后先按下 esc 键,再按下 : 键,在光标闪烁处输入:wq, 按回车,完成修改
- 设置执行权限。
输入命令:chmod +x /etc/rc.d/rc.local
chmod +x /myApp/test/startup.sh
-
在linux中输入命令 :reboot 。重启服务器
-
重启后,输入:ps -ef | grep jar 查看jar包是否启动
三、其他
上述步骤,如有错误的地方,欢迎大家指正交流。