配置java服务开机启动,和日志重定向

目的

  1. 配置spring java项目开机启动
  2. 服务运行日志能够重定向到自定义的文件

服务配置

systemd服务配置如下(参考了这个连接这个连接):

[Unit]
Description=app main service
After=network-online.target

[Service]
User=root
Group=root
WorkingDirectory=/data

# The JVM designers made Java return a non-zero exit code in case it is terminated by a system signal. As a non-zero base, they took 128, and the resulting exit code is a sum of 128 and the signal numeric value
# JVM状态码默认为128+退出码,如果是143(128+15),则代表正常退出,不重启进程.
SuccessExitStatus=143

#低版本systemctl(<240)需要通过/bin/bash重定向输出操作
#注意这里用`exec`,保证子命令会替换掉/bin/bash进程
ExecStart=/bin/bash -c 'exec /data/jdk1.8.0_381/bin/java -jar /data/app.jar 2>&1 > /data/log.out'
ExecStop=/bin/kill -15 $MAINPID
Restart=on-failure
RestartSec=60s

#高版本不需要通过/bin/bash代理执行,通过如下参数即可重定向服务输出
#StandardOutput=file:/data/log.out
#StandardError=file:/data/log.out

# 按照网上说法,bash -c会替换原进程,没有生成子进程,所以使用simple模式.
Type=simple

# 如果通过shell脚本启动,需要设置为forking模式,此时systemd可以跟踪子进程状态
# Type=forking

[Install]
WantedBy=multi-user.target

创建app.service文件,放置到/etc/systemd/system下,然后执行如下命令安装服务:

systemctl daemon-reload
systemctl enable app
systemctl start app

posted @ 2023-10-11 12:16  mosakashaka  阅读(100)  评论(0编辑  收藏  举报