Docker部署Spring-boot项目的示例代码

小编 2026-07-13 阅读:1208 评论:0
一、基础Spring-boot快速启动  1.1 快速启动 pom.xml加入如下依赖 <parent> <groupId>org.springframew...

一、基础Spring-boot快速启动

 1.1 快速启动 pom.xml加入如下依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
  </parent>

  <properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </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>
    <finalName>spring-docker</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

Spring-boot启动类

@SpringBootApplication
public class DockerApplication {

  public static void main(String[] args) {
    SpringApplication.run(DockerApplication.class, args);
  }
}

测试API

@RestController
public class DockerStarterApi {

  @GetMapping(\"/api/docker/hello\")
  public String hello() {
    return \"hello docker\";
  }
}

配置启动配置文件 application.yml

server:
 port: 9090 # 为了展示效果, 这里改了默认端口8080

检查Spring启动

.  ____     _      __ _ _
 /\\\\ / ___\'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\
( ( )\\___ | \'_ | \'_| | \'_ \\/ _` | \\ \\ \\ \\
 \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )
 \' |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::    (v2.0.2.RELEASE)

...

2018-12-17 17:26:13.385 INFO 48740 --- [      main] o.s.j.e.a.AnnotationMBeanExporter    : Registering beans for JMX exposure on startup
2018-12-17 17:26:13.448 INFO 48740 --- [      main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path \'\'
2018-12-17 17:26:13.453 INFO 48740 --- [      main] pers.study.docker.DockerApplication   : Started DockerApplication in 1.982 seconds (JVM running for 2.602)

检查API是否生效

$ curl -XGET \'http://localhost:9090/api/docker/hello\'
hello docker

浏览器检查

http://localhost:9090/api/docker/hello

\"\"

1.2 打包启动

项目打包

完成上面步骤之后,执行打包命令:

$ mvn clean -U -Dmaven.test.skip compile package

因为上面的pom文件里面定义了 finalName ,所以在这里会看到编译打包之后 target 目录下会生成 spring-docker.jar

<finalName>spring-docker</finalName>

测试运行

$ java -jar target/spring-docker.jar

不出意外(有问题留言~)运行结果同上并检查API是否生效即可.

二、Docker快速安装

接下来开始准备Docker

安装

官网下载安装

检查安装、查看帮助

$ docker --version
Docker version 18.06.0-ce, build 0ffa825

$ docker --help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
...

镜像加速

中国官方镜像加速

三、配置Spring-boot + Docker

pom.xml 添加docker plugin

<properties>
    <docker.image.prefix>springboot</docker.image.prefix>
  </properties>

  <build>
    <plugins>
      <!-- Docker maven plugin -->
      <plugin>
        <groupId>com.spotify</groupId>
        <artifactId>docker-maven-plugin</artifactId>
        <version>1.0.0</version>
        <configuration>
          <imageName>${docker.image.prefix}/${project.build.finalName}</imageName>
          <dockerDirectory>src/main/docker</dockerDirectory>
          <resources>
            <resource>
              <targetPath>/</targetPath>
              <directory>${project.build.directory}</directory>
              <include>${project.build.finalName}.jar</include>
            </resource>
          </resources>
        </configuration>
      </plugin>
    </plugins>
  </build>

创建 Dockerfile 文件

根据上面 pom.xml 文件配置 <dockerDirectory>src/main/docker</dockerDirectory> ,这里配置了docker配置文件的目录,所以需要再 src/main 下面创建docker文件夹,同时创建 Dockerfile 文件。

目录机构如图:

\"\"

docker配置文件结构.png

编辑 Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD spring-docker.jar app.jar
ENTRYPOINT [\"java\",\"-Djava.security.egd=file:/dev/./urandom\",\"-jar\",\"/app.jar\"]

FROM 表示以Java8为基础镜像

VOLUME 表示挂载目录

ADD 拷贝打包文件并重命名为 app.jar

ENTRYPOINT 根据下面的官方文档解释大致是为了缩短tomcat启动时间而添加的一个系统属性。

We added a VOLUME pointing to /tmp because that is where a Spring Boot application creates working directories for Tomcat by default. The effect is to create a temporary file on your host under /var/lib/docker and link it to the container under /tmp . This step is optional for the simple app that we wrote here but can be necessary for other Spring Boot applications if they need to actually write in the filesystem.

To reduce Tomcat startup time we added a system property pointing to \"/dev/urandom\" as a source of entropy. This is not necessary with more recent versions of Spring Boot, if you use the \"standard\" version of Tomcat (or any other web server).

配置完成!

四、Docker启动Spring-boot

进入 module 执行:

$ mvn package docker:build

[INFO] Scanning for projects...

...

 ---> Running in e1f8aba72bdf
Removing intermediate container e1f8aba72bdf
 ---> 36a61c09f09a
ProgressMessage{id=null, status=null, stream=null, error=null, progress=null, progressDetail=null}
Successfully built 36a61c09f09a
Successfully tagged springboot/spring-docker:latest
[INFO] Built springboot/spring-docker
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.367 s
[INFO] Finished at: 2018-12-17T20:48:21+08:00
[INFO] ------------------------------------------------------------------------

查看镜像

$ docker images
REPOSITORY         TAG         IMAGE ID      CREATED       SIZE
springboot/spring-docker  latest       36a61c09f09a    2 minutes ago    123MB

运行镜像

$ docker run -p 9090:9090 -t springboot/spring-docker
 .  ____     _      __ _ _
 /\\\\ / ___\'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\
( ( )\\___ | \'_ | \'_| | \'_ \\/ _` | \\ \\ \\ \\
 \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )
 \' |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::    (v2.0.2.RELEASE)

2018-12-17 12:53:21.502 INFO 1 --- [      main] pers.study.docker.DockerApplication   : Starting DockerApplication v1.0-SNAPSHOT on 94991c04be5d with PID 1 (/app.jar started by root in /)
2018-12-17 12:53:21.509 INFO 1 --- [      main] pers.study.docker.DockerApplication   : No active profile set, falling back to default profiles: default

···

2018-12-17 12:53:25.255 INFO 1 --- [      main] o.s.j.e.a.AnnotationMBeanExporter    : Registering beans for JMX exposure on startup
2018-12-17 12:53:25.337 INFO 1 --- [      main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path \'\'
2018-12-17 12:53:25.353 INFO 1 --- [      main] pers.study.docker.DockerApplication   : Started DockerApplication in 4.485 seconds (JVM running for 5.346)

查看容器

$ docker ps
CONTAINER ID    IMAGE           COMMAND         CREATED       STATUS       PORTS                                  NAMES
94991c04be5d    springboot/spring-docker  \"java -Djava.securit…\"  53 seconds ago   Up 52 seconds    0.0.0.0:9090->9090/tcp                          quizzical_bhabha

验证启动,访问API

$ curl -XGET \'http://localhost:9090/api/docker/hello\'
hello docker

至此Docker部署spring-boot搭建完成。

五、移除镜像

 停止容器

$ docker stop 94991c04be5d
94991c04be5d

删除容器

$ docker rm 94991c04be5d
94991c04be5d

删除镜像

$ docker image rm springboot/spring-docker
Untagged: springboot/spring-docker:latest
Deleted: sha256:36a61c09f09ab88cfe5a05f564deb57498682f4a6f3ec01d2a8c4fdc80ac1e41
Deleted: sha256:3f9aef70be6d4d43c205454d8874f10bc2f7280f70eb88cd1f04937b7965dd27
Deleted: sha256:9a5800e93615bb4c5128bb36d31ec494327c01f1a9a768c1ff538badf76628b9
Deleted: sha256:d9c66f907448fa9e61fd5f9267d7fcf8e1f4b52d0a20466414f2f45777261284

六、其他配置功能

添加环境属性

$ docker run -e \"SPRING_PROFILES_ACTIVE=prod\" -p 9090:9090 -t springbooot/spring-docker

后台启动运行

$ docker run -p 9090:9090 -d springboot/spring-docker

开启容器Debug 修改 Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD spring-docker.jar app.jar
ENV JAVA_OPTS \'\'
CMD java -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar app.jar

docker run

复制代码 代码如下:
$ docker run -e \"JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=5005,server=y,suspend=n\" -p 9090:9090 -p 5005:5005 -t springboot/spring-docker

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
标签列表