如何把java程序作为Linux服务启动

来源:互联网 发布:移动80端口 编辑:程序博客网 时间:2024/06/05 20:13

java程序作为Linux服务启动

前言

当作为服务启动之后,对于程序的管理更加简单方面了,通过命令行

systemctl start xxx.service //启动项目systemctl stop xxx.service //停止项目systemctl restart xxx.service //重启项目

而且当程序被异常关闭之后,服务会将程序自动拉起。

第一步服务脚本编写

[Unit]Description=test demo api service by javaDocumentation=https://www.xxxxx.comAfter=network.target[Service]User=nobody#Type=forkingPIDFile=/run/testDemoAPI.pidExecStart=/bin/sh -c '/usr/bin/java -jar /usr/local/src/testDemoAPI/testdemoapi.jar >> /var/log/testDemoApi.log 2>&1'SuccessExitStatus=143TimeoutStopSec=10Restart=on-failureRestartSec=5[Install]WantedBy=multi-user.target

第二步将应用程序放到指定的文件路径下

将程序jar包放到脚本中指定的路径下

mv testdemoapi.jar /usr/local/src/testDemoAPI/

第三步将写好的脚本放到系统服务目录下

mv test-demo-api.service /usr/lib/systemd/system/

第四步启动服务

systemctl start test-demo-api.service//启动服务时可能会因为没有权限创建/var/log/testDemoApi.log文件报错

使用命令行查看原因

运行命令行:systemctl status test-demo-api.service[root@localhost system]# systemctl status test-demo-api.service● base-info-api.service - base info api service by java   Loaded: loaded (/usr/lib/systemd/system/est-demo-api.service; disabled; vendor preset: disabled)   Active: activating (auto-restart) (Result: exit-code) since 三 2017-09-20 17:11:43 CST; 3s ago     Docs: https://www.hocyun.com  Process: 7496 ExecStart=/bin/sh -c /usr/bin/java -jar /usr/local/src/testDemoAPI/testdemoapi.jar >> /var/log/testDemoAPI.log 2>&1 (code=exited, status=1/FAILURE) Main PID: 7496 (code=exited, status=1/FAILURE)920 17:11:43 localhost.localdomain systemd[1]: Unit test-demo-api.service entered failed state.920 17:11:43 localhost.localdomain systemd[1]: test-demo-api.service failed.运行命令行:journalctl -xe得知:920 17:14:05 localhost.localdomain sh[7579]: /bin/sh: /var/log/testDemoAPI.log: 权限不够920 17:14:05 localhost.localdomain systemd[1]: base-info-api.service: main process exited, code=exited, status=1/FAILURE920 17:14:05 localhost.localdomain systemd[1]: Unit base-info-api.service entered failed state.920 17:14:05 localhost.localdomain systemd[1]: base-info-api.service failed.920 17:14:10 localhost.localdomain systemd[1]: base-info-api.service holdoff time over, scheduling restart.920 17:14:10 localhost.localdomain systemd[1]: Started base info api service by java.

我们帮他创建好这个日志文件并且将用户权限改为nobody

touch /var/log/testDemoAPI.log //创建文件chown nobody:nobody testDemoAPI.log//并且将文件权限改为nobody

第五步启动项目

systemctl start test-demo-api.service
阅读全文
1 0
原创粉丝点击