Ubuntu下部署SpringBoot

第一步: 安装java环境

1
2
3
4
5
6
# 更新软件源
sudo apt update
# 安装OpenJDK 17(开源免费,推荐)
sudo apt install openjdk-17-jdk
# 验证安装:输出JDK版本即成功
java -version

第二步: 安装下载Idea并新建SpringBoot项目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

在这里插入图片描述

第三步: 打包 .jar 文件

在这里插入图片描述

对于Maven 可以使用使令:mvn clean package
对于Gradle 可以使用使令:./gradlew clean bootJar

第四步: 在 Ubuntu 上部署 .jar 包

  • mkdir demo 命令创建一个名为 demo 的目录
  • cd demo 命令进入该目录
  • nohup java -jar demo-0.0.1-SNAPSHOT.jar 命令启动 jar 包。
    • nohup xxx & : 是 no hang up 的缩写,意为不挂起,用于在系统后台不断运行命令,退出终端不会影响程序的运行

    • 运行完之后会生成一个 nohup.out 文件,里面是启动过程的一些日志

    • 打开 nohup.out 文件,如果正常启动的话,会看到类似这样的输出

      Started DemoApplication in xxx seconds
      
    • 但是,我就没那么幸运了,我遇到的是这样的

          .   ____          _            __ _ _
          /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
          ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
          \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
          '  |____| .__|_| |_|_| |_\__, | / / / /
          =========|_|==============|___/=/_/_/_/
          :: Spring Boot ::                (v2.5.2)
      
          2021-07-14 22:42:22.087  INFO 39193 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT using Java 1.8.0_291 on iZwz92d94t8mb03s9z327hZ with PID 39193 (/opt/xiaodudu/demo/demo-0.0.1-SNAPSHOT.jar started by root in /opt/xiaodudu/demo)
          2021-07-14 22:42:22.090  INFO 39193 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
          2021-07-14 22:42:23.276  INFO 39193 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
          2021-07-14 22:42:23.291  INFO 39193 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
          2021-07-14 22:42:23.291  INFO 39193 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.48]
          2021-07-14 22:42:23.345  INFO 39193 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
          2021-07-14 22:42:23.345  INFO 39193 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1141 ms
          2021-07-14 22:42:23.673  WARN 39193 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.PortInUseException: Port 8080 is already in use
          2021-07-14 22:42:23.677  INFO 39193 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
          2021-07-14 22:42:23.691  INFO 39193 --- [           main] ConditionEvaluationReportLoggingListener : 
      
          Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
          2021-07-14 22:42:23.713 ERROR 39193 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 
      
          ***************************
          APPLICATION FAILED TO START
          ***************************
      
          Description:
      
          Web server failed to start. Port 8080 was already in use.
      
          Action:
      
          Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.        
      
      • Port 8080 was already in use. 端口被占用,是比较常见的一个异常。

      • 执行 netstat -anp | grep 8080 查看占用端口的程序 pid。(netstat 有很多参数,可以使用 netstat -h 查询)

        root@iZwz92d94t8mb03s9z327hZ:~# netstat -anp | grep 8080
        tcp6       0      0 :::8080                 :::*                    LISTEN      19032/java
        
      • 执行 kill -9 xxxxx 命令终止该程序

        root@iZwz92d94t8mb03s9z327hZ:~# kill -9 19032
        
      • 重新执行 nohup xxx & 命令部署 jar 程序。(nohup.out 是否删除可以自己决定,删除就是重新生成,不删除就是追加内容)

        root@iZwz92d94t8mb03s9z327hZ:/opt/xiaodudu/demo# nohup java -jar demo-0.0.1-SNAPSHOT.jar &
        [1] 39342
        root@iZwz92d94t8mb03s9z327hZ:/opt/xiaodudu/demo# nohup: ignoring input and appending output to 'nohup.out'
        
      • 查看 nohup.out 文件

             .   ____          _            __ _ _
            /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
            ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
            \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
            '  |____| .__|_| |_|_| |_\__, | / / / /
            =========|_|==============|___/=/_/_/_/
            :: Spring Boot ::                (v2.5.2)
        
            2021-07-14 23:05:16.089  INFO 39342 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT using Java 1.8.0_291 on iZwz92d94t8mb03s9z327hZ with PID 39342 (/opt/xiaodudu/demo/demo-0.0.1-SNAPSHOT.jar started by root in /opt/xiaodudu/demo)
            2021-07-14 23:05:16.093  INFO 39342 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
            2021-07-14 23:05:17.228  INFO 39342 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
            2021-07-14 23:05:17.239  INFO 39342 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
            2021-07-14 23:05:17.240  INFO 39342 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.48]
            2021-07-14 23:05:17.300  INFO 39342 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
            2021-07-14 23:05:17.300  INFO 39342 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1095 ms
            2021-07-14 23:05:17.755  INFO 39342 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
            2021-07-14 23:05:17.764  INFO 39342 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 2.338 seconds (JVM running for 2.769)
        

远程访问接口

  • 访问 Ubuntu 服务器IP: 8080/hello/springboot

在这里插入图片描述

第五步: 在 Ubuntu 上使用进程管理

直接用 java -jar 启动的应用在终端关闭后会终止,且意外崩溃后无法自动重启。
可使用进程管理工具(systemd)确保应用后台运行并自动恢复,通过系统服务管理 JAR 应用,支持开机自启、状态监控、日志管理。

1.创建服务文件(如 /etc/systemd/system/myapp.service):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[Unit]
Description=My Spring Boot Application
After=network.target

[Service]
User=formeasy
Group=formeasy

#WorkingDirectory=/opt/xiaodudu/demo/ # JAR 文件所在目录,建议不注释
ExecStart=/usr/bin/java -jar /opt/xiaodudu/demo/demo-0.0.1-SNAPSHOT.jar --server.port=8080
SuccessExitStatus=143 # 兼容 Spring Boot 的优雅退出码
Restart=always # 崩溃后自动重启
RestartSec=5 # 重启间隔(秒)

[Install]
WantedBy=multi-user.target

2.启用并启动服务:

1
2
3
sudo systemctl daemon-reload  # 刷新配置
sudo systemctl start myapp # 启动应用
sudo systemctl enable myapp # 设置开机自启

3.常用命令:

1
2
3
sudo systemctl status myapp  # 查看状态
sudo systemctl stop myapp # 停止应用
journalctl -u myapp -f # 实时查看日志

4.如果出错,按照以下排查:

  1. 检查目录和文件是否存在
1
2
3
4
5
6
7
8
9
# 检查工作目录是否存在
ls -la /opt/xiaodudu/demo/

# 检查 JAR 文件是否存在
ls -la /opt/xiaodudu/demo/demo-0.0.1-SNAPSHOT.jar

# 检查 Java 安装
which java
java -version
  1. 创建缺失的目录和权限
1
2
3
4
5
6
7
8
# 创建应用目录
sudo mkdir -p /opt/xiaodudu/demo/

# 设置正确的权限
sudo chown -R formeasy:formeasy /opt/xiaodudu/demo/

# 确保 JAR 文件在正确的位置
# 如果还没有,上传或复制您的 JAR 文件到这个目录