进行了这么长时间SpringBoot项目开发,今天想系统的总结一下项目部署到linux服务器的流程,并在上一篇介绍了linux环境的准备与搭建,SpringBoot项目部署到linux服务器之环境搭建,这篇记录一下从git上拉取项目,并写脚本启动项目,访问项目。
一、从git拉取项目
前提是已经将项目上传到git仓库,我的举例项目上传到了github上,或者是本地打成jar并上传到linux服务器,本篇以从git仓库拉取为例。
新建一个目录并执行如下:
[root@localhost zrk]# git clone https://github.com/zrk333/myboot.git
会生成myboot文件夹,进入文件夹(cd myboot)
二、编译打包
打包编译后文件如下:
[root@localhost myboot]# mvn clean install
[root@localhost myboot]# ls
myboot.iml nohup.out pom.xml README.md src target
三、启动项目
进入target文件夹下
[root@localhost myboot]# cd target
[root@localhost target]# ls
classes generated-test-sources maven-status myboot-0.0.1-SNAPSHOT.jar.original test-classes
generated-sources maven-archiver myboot-0.0.1-SNAPSHOT.jar surefire-reports
1)可以使用java -jar 启动
[root@localhost target]# java -jar myboot-0.0.1-SNAPSHOT.jar
2)可以使用nohup后台启动
[root@localhost target]# nohup java -jar myboot-0.0.1-SNAPSHOT.jar &
- 可以写脚本启动
为了方便以后提交代码后重启项目,可以写脚本进行重启,可以参考四、编写启动脚本
四、编写启动脚本
1)回到myboot目录,并创建start文件
[root@localhost target]# cd ..
[root@localhost myboot]# touch start
2)编写启动脚本
[root@localhost myboot]# vi start
插入如下内容:(部分参数需要根据实际情况调整,比如项目名称,使用的环境等)
#!/bin/sh
git pull
mvn clean install
echo "restart application"
ps -ef | grep myboot | grep -v grep | awk '{print $2}' | xargs kill -9
nohup java -jar -Dspring.application.name=myboot -Dspring.profiles.active=dev target/myboot-0.0.1-SNAPSHOT.jar &
3)执行脚本
[root@localhost myboot]# ./start
最终截图(片段)如下:
4) 添加权限
第一次执行应该会有如下提示:
[root@localhost myboot]# ./start
-bash: ./start: Permission denied
需要执行如下命令才行:
[root@localhost myboot]# sudo chmod -R 777 start
五、访问项目
1)使用浏览器或者postman用ip:port+url访问:
2)查看服务器ip地址
[root@localhost myboot]# ip addr
3) 如果访问失败,可能是因为端口没有开发,可以关闭防火墙
- 1服务器访问测试
[root@localhost myboot]# curl localhost:8081/user/getUserInfo?id=1
{"id":1,"name":"张三","password":"123456"}[root@localhost myboot]
- 2关闭防火墙(方式不唯一,可以参考其他资料)
执行如下命令即可:
systemctl stop firewalld
整体流程应该差不多了,可以有时间的时候玩一下,仅供参考!