最近項目用到spring boot,看了官方文檔,可以把spring boot的jar包安裝爲一個service,直接用service serviceName start/stop/status/restart來控制。還可以設置開機自動啓動,這樣可以防止進程被殺掉。
可以:
1. Starts the services as the user that owns the jar file
2. Tracks application’s PID using /var/run/appname.pid
3. Writes console logs to /var/log/appname.log
但是按照教程配置之後service myapp start啓動時一直報Unit myapp.service not found。找了很久才找到解決辦法。
打包
用maven打包舉例,plugin加上參數
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
這個可以打包爲可執行文件,用./myapp.jar可以直接執行,而不用一般的java -jar。
註冊服務
接下來需要把服務註冊到init.d。
在這之前需要修改文件的權限爲可執行
chmod 755 myapp.jar
註冊服務很簡單,只需要創建一個連接
ln -s /myfolder/myapp/myapp.jar /etc/init.d/myapp
啓動
按照教程上的說法,這樣就可以直接用命令啓動服務了
service myapp start
但是在我這裏一直報錯Unit myapp.service not found
trouble shooting
雖然用service myapp start
不能啓動,但是可以用/etc/init.d/myapp start
成功啓動。
在網上看了很多帖子,最後嘗試執行了
update-rc.d myapp defaults
成功~
這個命令在spring boot文檔裏是用來註冊開機自動啓動的,不是很理解爲什麼要執行這個纔可以。
jar包更新
jar包更新後需要執行systemctl daemon-reload
更新服務。
附上Spring boot文檔
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/html/deployment-install.html#deployment-systemd-service