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

java程序作为Linux服务启动

前言

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

systemctl start xxx.service //启动项目

systemctl stop xxx.service //停止项目

systemctl restart xxx.service //重启项目

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

第一步服务脚本编写
[Unit]
Description=test demo api service by java
Documentation=https://www.xxxxx.com
After=network.target

[Service]
User=nobody
#Type=forking
PIDFile=/run/testDemoAPI.pid
ExecStart=/bin/sh -c '/usr/bin/java -jar /usr/local/src/testDemoAPI/testdemoapi.jar >> /var/log/testDemoApi.log 2>&1'
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=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/FAILURE
920 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
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值