Ubuntu 18.04下不再使用initd而改用systemd,用systemctl命令替换了service和chkconfig。比如以前启动MySQL服务用:
sudo service mysql start
1
sudoservicemysqlstart
现在则用:
sudo systemctl start mysqld.service
1
sudosystemctlstartmysqld.service
systemctl service服务文件夹在/lib/systemd/system(基本服务文件夹)与/etc/systemd/system(开机启动文件夹)。在/lib/systemd/system下创建ppm.service,内容如下:
[Unit]
Description=ppm service
After=syslog.target
[Service]
ExecStart=/usr/lib/jvm/java-8-openjdk-amd64/bin/java -jar /home/ppm/ppm.jar --spring.profiles.active=pro > /dev/null 2>&1 & > out.log &
ExecReload=/usr/lib/jvm/java-8-openjdk-amd64/bin/java -jar /home/ppm/ppm.jar --spring.profiles.active=pro > /dev/null 2>&1 & > out.log &
ExecStop=/usr/lib/jvm/java-8-openjdk-amd64/bin/java -jar /home/ppm/ppm.jar --spring.profiles.active=pro > /dev/null 2>&1 & > out.log &
PrivateTmp=true
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
Alias=ppm.service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Unit]
Description=ppmservice
After=syslog.target
[Service]
ExecStart=/usr/lib/jvm/java-8-openjdk-amd64/bin/java-jar/home/ppm/ppm.jar--spring.profiles.active=pro>/dev/null2>&1&>out.log&
ExecReload=/usr/lib/jvm/java-8-openjdk-amd64/bin/java-jar/home/ppm/ppm.jar--spring.profiles.active=pro>/dev/null2>&1&>out.log&
ExecStop=/usr/lib/jvm/java-8-openjdk-amd64/bin/java-jar/home/ppm/ppm.jar--spring.profiles.active=pro>/dev/null2>&1&>out.log&
PrivateTmp=true
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
Alias=ppm.service
其中:
[Unit]段,定义启动顺序与依赖关系,如After=network.target就说明在network.target服务启动之后;
[Service]段,定义服务行为;
[Install]段:,定义如何安装这个配置文件,即怎样做到开机启动;
运行如下命令让服务生效:
sudo systemctl daemon-reload
1
sudosystemctldaemon-reload
然后运行:
sudo systemctl start ppm.service
1
sudosystemctlstartppm.service
如果想开机启动,则运行:
sudo systemctl enable ppm.service
1
sudosystemctlenableppm.service
这个时候系统会自动加载ppm.service到/etc/systemd/system文件夹下(不推荐通过ln链接过去)。
如果systemctl start遇到问题则可以通过:
systemctl status ppm.service
1
systemctlstatusppm.service
查看原因。
需要注意,ExecStart中需要使用绝对路径。另外,对于Spring Boot应用而言:
SuccessExitStatus=143
1
SuccessExitStatus=143
是必须的。
参考文档:
1、https://www.auroria.io/spring-boot-as-systemd-service/
2、https://stackoverflow.com/questions/22886083/how-do-i-run-a-spring-boot-executable-jar-in-a-production-environment