如何把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

你可能感兴趣的:(linux运维,java,linux,linux服务)