Spring Boot 2 (四):使用 Docker 部署 Spring Boot - 纯洁的微笑博客

Docker 技术发展为微服务落地提供了更加便利的环境,使用 Docker 部署 Spring Boot 其实非常简单,这篇文章我们就来简单学习下。

首先构建一个简单的 Spring Boot 项目,然后给项目添加 Docker 支持,最后对项目进行部署。

一个简单 Spring Boot 项目

pom.xml 中 ,使用 Spring Boot 2.0 相关依赖

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

添加 web 和测试依赖

<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>

创建一个 DockerController,在其中有一个index()方法,访问时返回:Hello Docker!

@RestController
public class DockerController {
    
    @RequestMapping("/")
    public String index() {
        return "Hello Docker!";
    }
}

启动类

@SpringBootApplication
public class DockerApplication {

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

添加完毕后启动项目,启动成功后浏览器放问:http://localhost:8080/,页面返回:Hello Docker!,说明 Spring Boot 项目配置正常。

Spring Boot 项目添加 Docker 支持

pom.xml-properties 中添加 Docker 镜像名称

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

plugins 中添加 Docker 构建插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!-- Docker maven plugin -->
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>1.0.0</version>
            <configuration>
                <imageName>${docker.image.prefix}/${project.artifactId}</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>
        <!-- Docker maven plugin -->
    </plugins>
</build>

在目录src/main/docker下创建 Dockerfile 文件,Dockerfile 文件用来说明如何来构建镜像。

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

这个 Dockerfile 文件很简单,构建 Jdk 基础环境,添加 Spring Boot Jar 到镜像中,简单解释一下:

  • FROM ,表示使用 Jdk8 环境 为基础镜像,如果镜像不是本地的会从 DockerHub 进行下载
  • VOLUME ,VOLUME 指向了一个/tmp的目录,由于 Spring Boot 使用内置的Tomcat容器,Tomcat 默认使用/tmp作为工作目录。这个命令的效果是:在宿主机的/var/lib/docker目录下创建一个临时文件并把它链接到容器中的/tmp目录
  • ADD ,拷贝文件并且重命名
  • ENTRYPOINT ,为了缩短 Tomcat 的启动时间,添加java.security.egd的系统属性指向/dev/urandom作为 ENTRYPOINT
这样 Spring Boot 项目添加 Docker 依赖就完成了。

构建打包环境

我们需要有一个 Docker 环境来打包 Spring Boot 项目,在 Windows 搭建 Docker 环境很麻烦,因此我这里以 Centos 7 为例。

安装 Docker 环境

安装

yum install docker

安装完成后,使用下面的命令来启动 docker 服务,并将其设置为开机启动:

service docker start
chkconfig docker on

#LCTT 译注:此处采用了旧式的 sysv 语法,如采用CentOS 7中支持的新式 systemd 语法,如下:
systemctl  start docker.service
systemctl  enable docker.service

使用Docker 中国加速器

vi  /etc/docker/daemon.json

#添加后:
{
    "registry-mirrors": ["https://registry.docker-cn.com"],
    "live-restore": true
}

重新启动docker

systemctl restart docker

输入docker version 返回版本信息则安装正常。

安装JDK

yum -y install java-1.8.0-openjdk*

配置环境变量 打开 vim /etc/profile 添加一下内容

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64 
export PATH=$PATH:$JAVA_HOME/bin 

修改完成之后,使其生效

source /etc/profile

输入java -version 返回版本信息则安装正常。

安装MAVEN

下载:http://mirrors.shu.edu.cn/apache/maven/maven-3/3.5.2/binaries/apache-maven-3.5.2-bin.tar.gz

## 解压
tar vxf apache-maven-3.5.2-bin.tar.gz
## 移动
mv apache-maven-3.5.2 /usr/local/maven3

修改环境变量, 在/etc/profile中添加以下几行

MAVEN_HOME=/usr/local/maven3
export MAVEN_HOME
export PATH=${PATH}:${MAVEN_HOME}/bin

记得执行source /etc/profile使环境变量生效。

输入mvn -version 返回版本信息则安装正常。

这样整个构建环境就配置完成了。

使用 Docker 部署 Spring Boot 项目

将项目 spring-boot-docker 拷贝服务器中,进入项目路径下进行打包测试。

#打包
mvn package
#启动
java -jar target/spring-boot-docker-1.0.jar

看到 Spring Boot 的启动日志后表明环境配置没有问题,接下来我们使用 DockerFile 构建镜像。

mvn package docker:build

第一次构建可能有点慢,当看到以下内容的时候表明构建成功:

...
Step 1 : FROM openjdk:8-jdk-alpine
 ---> 224765a6bdbe
Step 2 : VOLUME /tmp
 ---> Using cache
 ---> b4e86cc8654e
Step 3 : ADD spring-boot-docker-1.0.jar app.jar
 ---> a20fe75963ab
Removing intermediate container 593ee5e1ea51
Step 4 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Running in 85d558a10cd4
 ---> 7102f08b5e95
Removing intermediate container 85d558a10cd4
Successfully built 7102f08b5e95
[INFO] Built springboot/spring-boot-docker
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 54.346 s
[INFO] Finished at: 2018-03-13T16:20:15+08:00
[INFO] Final Memory: 42M/182M
[INFO] ------------------------------------------------------------------------

使用docker images命令查看构建好的镜像:

docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
springboot/spring-boot-docker   latest              99ce9468da74        6 seconds ago       117.5 MB

springboot/spring-boot-docker 就是我们构建好的镜像,下一步就是运行该镜像

docker run -p 8080:8080 -t springboot/spring-boot-docker

启动完成之后我们使用docker ps查看正在运行的镜像:

docker ps
CONTAINER ID        IMAGE                           COMMAND                  CREATED             STATUS              PORTS                    NAMES
049570da86a9        springboot/spring-boot-docker   "java -Djava.security"   30 seconds ago      Up 27 seconds       0.0.0.0:8080->8080/tcp   determined_mahavira

可以看到我们构建的容器正在在运行,访问浏览器:http://192.168.0.x:8080/,返回

Hello Docker!

说明使用 Docker 部署 Spring Boot 项目成功!

示例代码-github

示例代码-码云

参考

Spring Boot with Docker
Docker:Spring Boot 应用发布到 Docker


扫码关注有惊喜

(转载本站文章请注明作者和出处 纯洁的微笑-ityouknow

Show Disqus Comments

45 条评论

未登录用户

支持 Markdown 语法使用 Github 登录

头像

xiah217发表于大约 1 年前

你好,请问你是用什么工具将项目拷贝服务器中的?谢谢

头像

ityouknow发表于大约 1 年前

@xiah217 什么都可以呀, ssh工具,rz等

头像

xiah217发表于大约 1 年前

@ityouknow
@xiah217 什么都可以呀, ssh工具,rz等

谢谢你,博主好人,将康快乐

头像

kakadai发表于大约 1 年前

winscp应该也可以吧

头像

TanqiZhou发表于大约 1 年前

我想知道日志去哪里了

头像

ityouknow发表于大约 1 年前

@TanqiZhou 就在容器里面

头像

xiah217发表于大约 1 年前

为什么在用mvn package docker:build构建镜像的时候一直显示 Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/3.1.1/maven-archiver-3.1.1.pom

头像

youarepppp发表于大约 1 年前

你的文档应该再进一步,加入用docker-compose的部分

头像

xiah217发表于大约 1 年前

@youarepppp
你的文档应该再进一步,加入用docker-compose的部分

博主已经写了相关的,你自己找

头像

wubodanran发表于大约 1 年前

docker run -p 7106:7106 -t springboot/spring-boot-docker 他不会后台运行唉

头像

ityouknow发表于大约 1 年前

@wubodanran 加上 -d 参数,类似下面:

docker run -d -p 7106:7106 -t springboot/spring-boot-docker

头像

xiah217发表于大约 1 年前

博主,我写了两个不相关的项目a和b,分别已经得到对应的镜像springboot/a 和 springboot/b,为什么我只能docker run一个镜像,当运行另外一个镜像时就会把前面跑起来的镜像挤下去,端口没有冲突,谢谢你!

头像

WinterChenS发表于12 个月前

太详细了,赞个

头像

kely39发表于10 个月前

mvn package docker:build时报错:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:17 min
[INFO] Finished at: 2018-06-05T17:18:11+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project springboot-docker-demo: Exception caught: java.util.concurrent.ExecutionException: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException: Cannot retry request with a non-repeatable request entity: Connection reset by peer -> [Help 1]

怎么破?

头像

gistmap发表于10 个月前

为什么是在centos中安装环境,不是用docker镜像安装。

头像

kely39发表于10 个月前

@gistmap
为什么是在centos中安装环境,不是用docker镜像安装。

maven和jdk都不是镜像安装的,有问题吗?

头像

chyitboy发表于10 个月前

docker 安装mysql其他机器访问没问题,部署到本机就不行了,这么咋搞

头像

kely39发表于10 个月前

我的也没成功之后还没去跟踪了,你的maven是镜像安装的吗?

在 2018年6月29日,00:55,王小伟 @.*> 写道: 您好,我按照您的教程来学习的,当执行到 mvn package docker:build 这个步骤时, 其中第三步拷贝文件时发生了错误。 Step 3/4 : ADD spring-boot-docker-1.0.jar app.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 47.904 s [INFO] Finished at: 2018-06-28T12:13:26+08:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project springboot-docker: Exception caught: ADD failed: stat /var/lib/docker/tmp/docker-builder804713190/spring-boot-docker-1.0.jar: no such file or directory -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. 我已经把我运行的代码上传到github,地址: https://github.com/huowolf/springboot/tree/master/springboot-docker。 麻烦你有时间的时候指正一下我哪里错误了,不胜感谢!!学习啦!! — You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.

头像

huowolf发表于10 个月前

@kely39
我的也没成功之后还没去跟踪了,你的maven是镜像安装的吗?

在 2018年6月29日,00:55,王小伟 notifications@github.com 写道:

您好,我按照您的教程来学习的,当执行到 mvn package docker:build 这个步骤时,
其中第三步拷贝文件时发生了错误。
Step 3/4 : ADD spring-boot-docker-1.0.jar app.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 47.904 s [INFO] Finished at: 2018-06-28T12:13:26+08:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project springboot-docker: Exception caught: ADD failed: stat /var/lib/docker/tmp/docker-builder804713190/spring-boot-docker-1.0.jar: no such file or directory -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
我已经把我运行的代码上传到github,地址: https://github.com/huowolf/springboot/tree/master/springboot-docker。
麻烦你有时间的时候指正一下我哪里错误了,不胜感谢!!学习啦!!


You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.

你好,我已经参照本篇博文操作成功了。
Maven不是安装的docker镜像,而是直接安装在你的远程Linux服务器上的。

头像

huowolf发表于10 个月前

@gistmap
为什么是在centos中安装环境,不是用docker镜像安装。

我的理解:因为需要在远程服务器上手动使用Maven构建docker镜像,所以需要Maven环境,而maven环境依赖于Java环境。所以Java和Maven都需要你自己安装了。

头像

liqimoon发表于9 个月前

@huowolf

@gistmap
为什么是在centos中安装环境,不是用docker镜像安装。

我的理解:因为需要在远程服务器上手动使用Maven构建docker镜像,所以需要Maven环境,而maven环境依赖于Java环境。所以Java和Maven都需要你自己安装了。

我也参照本篇博文操作成功了。我的理解是:项目还是需要自己构建,pom中的docker-maven-plugin 只是在maven打完包后将打包后的内容利用插件中配置的参数 结合docker:build命令构建docker镜像发布到docker容器中,当容器中存在我们已经发布上去的项目时,直接运行docker run启动即可。关于项目的构建还是需要在本地构建才行,docker-maven-plugin只是当本地(本地已安装docker环境)执行docker:build时传递相关的参数。

头像

java-aodeng发表于9 个月前

学完去装逼

头像

lijinghao1997发表于9 个月前

Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project huiliang: Exception caught: com.spotify.docker.client.shaded.com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.spotify.docker.client.messages.RegistryAuth: no String-argument constructor/factory method to deserialize from String value ('swarm')

按照博主的方法进行构建,但是报了这个错误不知道有没有大神看一下

头像

chencong-plan发表于8 个月前

[INFO] Copying /developer/repository/springboot-docker/target/springboot-0.0.1-SNAPSHOT.jar -> /developer/repository/springboot-docker/target/docker/springboot-0.0.1-SNAPSHOT.jar
[INFO] Copying src/main/docker/Dockerfile -> /developer/repository/springboot-docker/target/docker/Dockerfile
[INFO] Building image springboot/springboot
Step 1/4 : FROM openjdk:8-jdk-alpine
 ---> 5801f7d008e5
Step 2/4 : VOLUME /tmp
 ---> Using cache
 ---> d5a539e5511f
Step 3/4 : ADD spring-boot-docker-1.0.jar app.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 33.405 s
[INFO] Finished at: 2018-08-13T14:09:45+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:0.4.13:build (default-cli) on project springboot: Exception caught: lstat spring-boot-docker-1.0.jar: no such file or directory -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

我也出现异常了 在执行mvn package docker:build这一步

头像

derkeeUser发表于8 个月前

细节可以参考这个:https://blog.csdn.net/caox_nazi/article/details/78366584

头像

zhangdp发表于8 个月前

请问当springboot项目更新的时候如何重新部署?难道每次都要重新创建运行docker镜像吗?再比如ADD ./nginx.conf /etc/nginx/nginx.conf,当修改了./nginx.conf文件的时候如何重新生效?

头像

cuisea发表于7 个月前

学习了

头像

huang-yuan发表于7 个月前

首先要有一台linux服务器

头像

JellyB发表于6 个月前

嗯,讲的不错!

头像

wuqiupeng发表于6 个月前

mvn package docker:build 报异常的,把docker-maven-plugin插件版本改成0.4.11就可以了(Mac ,linux好像没问题)

头像

damangueyu发表于5 个月前

博主
dockerfile 中
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
java -jar /app.jar 是什么意思?

ADD springboot.jar app.jar
app.jar是什么意思? 求解答

头像

linux-chaina发表于4 个月前

请问怎么开启远程debug
启动的时候加了这个参数 docker run -e "JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=5005,server=y,suspend=n"

报错:Error: Could not find or load main class $JAVA_OPTS

头像

siling5998发表于3 个月前

很棒的分享

头像

nainiu888发表于3 个月前

@kely39
mvn package docker:build时报错:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:17 min
[INFO] Finished at: 2018-06-05T17:18:11+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project springboot-docker-demo: Exception caught: java.util.concurrent.ExecutionException: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException: Cannot retry request with a non-repeatable request entity: Connection reset by peer -> [Help 1]

怎么破?
检查你的pom构建文件中标签值是否有大写字母。。无意间加了的大写字母问题排除了一个多小时。。。。

头像

Retr007发表于3 个月前

FROM openjdk:8-jdk-alpine
这个好像访问不了了

头像

Retr007发表于3 个月前

Step 1/4 : FROM openjdk:8-jdk-alpine
[INFO]
[ERROR] Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
[WARNING] An attempt failed, will retry 1 more times
org.apache.maven.plugin.MojoExecutionException: Could not build image

被屏蔽了这是,还有别的吗?

头像

nobt854发表于大约 2 个月前

建议安装maven的时候修改maven的settings.xml更改下载地址,使用国内镜像,如阿里

头像

Yoking-Wi发表于大约 1 个月前

maven 安装地址404

头像

Yoking-Wi发表于大约 1 个月前

补充maven-3.6.0 安装地址

https://www-us.apache.org/dist/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.tar.gz 

头像

PixelFrame发表于28 天前

在ArchLinux虚拟机里docker跑得好好的,save再import进Windows的docker就No command specified了..

头像

xhyrzldf发表于28 天前

@lijinghao1997
Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project huiliang: Exception caught: com.spotify.docker.client.shaded.com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.spotify.docker.client.messages.RegistryAuth: no String-argument constructor/factory method to deserialize from String value ('swarm')

按照博主的方法进行构建,但是报了这个错误不知道有没有大神看一下

将docker插件版本改为1.2.0版本

头像

TodayIsSunShine发表于19 天前

@damangueyu
博主
dockerfile 中
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
java -jar /app.jar 是什么意思?

ADD springboot.jar app.jar
app.jar是什么意思? 求解答

别名

头像

TodayIsSunShine发表于19 天前

docker部署有什么好处吗?直接执行jar不也可以吗,麻烦大佬回答下。。。

头像

TodayIsSunShine发表于19 天前

Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.0.0.RELEASE:repackage (default) on project spring-boot-docker: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.0.RELEASE:repackage failed: Unable to find main class -> [Help 1]
@ityouknow 大佬,这是什么错误

头像

godchou发表于17 天前

ADD spring-boot-docker-1.0-SNAPSHOT.jar app.jar


Original url: Access
Created at: 2019-04-15 11:32:51
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论