dockerfile-maven-plugin极简教程
⽬录
⼀、简介
maven是⼀个项⽬依赖管理和构建的⼯具,dockerfile-maven-plugin是⼀个maven的插件,主要作⽤是在项⽬构建的时候⽣成基于项⽬的docker镜像⽂件。
简⽽⾔之,此插件将maven和docker进⾏集成。
正常情况下,我们在开发了⼀个应⽤程序后,会使⽤maven进⾏打包,⽣成对应的jar⽂件。⽽后,会使⽤docker将jar⽂件build成⼀个镜像(docker image)。之后,就可以在docker daemon中创建基于镜像的容器,并可提供服务了。
dockerfile-maven-plugin的⽬标就是将maven的打包过程和docker的build过程结合在⼀起,当成功打包,既⽣成了对应的jar,也已⽣成了对应的docker镜像。当然,这只是最基础的功能,更详细的功能参见:
⼆、概述
我们知道maven是apache公司开发的⼀个产品,但是dockerfile-maven-plugin并不是apache官⽅开发的插件,是由⼀个叫做Spotify的组织开发的。
github主页:
github开源地址:
本⽂仅讨论如何基于⼀个Spring Boot的项⽬⽣成对应的docker镜像。
基本的原理如下:
⾸先,dockerfile-maven-plugin插件已经存储在maven的仓库中
然后,当在本地开发的时候,需要在项⽬的pom⽂件中引⼊此插件,在pom-build-plugins下⾯增加plugin配置节点
再然后,在executions节点中配置此插件如何⼯作;并且在configuration节点中加⼊需要的配置信息
最后,当我们执⾏mvn package的时候就可以得到docker image 了
环境:
Ideal版本:2020.01
java版本:8
maven版本:3.6.1
docker版本:19.03.12
ideal和docker deamon运⾏在同⼀台机器上⾯
三、将spring-boot-app打包成docker镜像
创建⽰例应⽤
使⽤ideal⾃带的Spring Initializr⽣成⼀个Spring Web 的⽰例项⽬
app对外提供⼀个hello的接⼝,访问该接⼝可以得到Hello,World的响应结果。应⽤主启动类代码如下:
package com.naylor.dockerfilemavenplugin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
@SpringBootApplication
public class DockerfileMavenPluginApplication {
public static void main(String[] args) {
SpringApplication.run(DockerfileMavenPluginApplication.class, args);
}
@GetMapping("/hello")
public  String hello(){
return  "Hello,World";
}
}
编译并运⾏项⽬,在浏览器中访问「 可以得到预期的响应结果
修改pom⽂件
<!--  dockerfile-maven-plugin      -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.3.6</version>
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>com.naylor/${project.artifactId}</repository>
<tag>${project.version}</tag>
<buildArgs>
<JAR_FILE>${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
其中:
g,a,v 为对插件的引⽤
executions中的build标识,在maven的packege环节执⾏此插件
configuration中的repository是⽣成的镜像的repository信息
tag为镜像的tag信息
buildArgs是在docker构建镜像过程中的参数,此处定义的JAR_FILE参数在执⾏docker build 的时候会消费
完整的pom⽂件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"        xsi:schemaLocation="/POM/4.0.0 /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.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.naylor</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dockerfile-maven-plugin</name>
<description>Demo project for Spring Boot</description>
<properties>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<!--  dockerfile-maven-plugin      -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.3.6</version>
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
</goals>
</execution>
maven下载教程</executions>
<configuration>
<repository>com.naylor/${project.artifactId}</repository>
<tag>${project.version}</tag>
<buildArgs>
<JAR_FILE>${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>
增加Dockerfile⽂件
在项⽬根⽬录(和pom⽂件在同⼀级)新建⼀个Dokerfile⽂件,⽂件内容如下:
FROM java:8
EXPOSE 8080
ARG JAR_FILE
ADD target/${JAR_FILE} /app.jar
ENTRYPOINT ["java", "-jar","/app.jar"]
使⽤Maven打包应⽤
⾸先清理⼀下maven⼯程,在ideal的Maven⾯版中点击Lifecycle-clean或者使⽤命令⾏执⾏mvn clean。
然后,使⽤maven构建app,在ideal的Maven⾯版中点击Liftcycle-package或者使⽤命令⾏执⾏ mvn package
再然后在命令⾏⼯具中执⾏docker image ls ,如果不出意外,可以看到⼀个repository为com.naylor/dockerfile-maven-plugin的docker镜像。
运⾏应⽤镜像
在命令⾏⼯具中执⾏如下命令运⾏容器:
docker run -d -p 8081:8080 ImageId
ImageId为上⼀步⽣成的镜像的id,每次⽣成的镜像id都不⼀样
此命令作⽤为基于ImageId构建⼀个容器,将宿主机的8081端⼝映射到容器的8080端⼝
在宿主机浏览器中访问「
四、分析mvn package 命令的控制台输出
通过mvn package的控制台输出,我们可以清晰的观察到整个流程的执⾏步骤,完整的输出如下:
_Springboot/debris-app "-Dmaven.home=/Applications/IntelliJ IDEA 2.app/Contents/plugins/maven/lib/maven3" "-f=/Applications/I ntelliJ IDEA 2.app/Contents/plugins/maven/lib/maven3/f" "-lass.path=/Applications/IntelliJ IDEA 2.app/Contents/plugins/ma ven/lib/maven-event-listener.jar" "-javaagent:/Applications/IntelliJ IDEA 2.app/Contents/lib/idea_rt.jar=58649:/Applications/IntelliJ IDEA 2.app/Conte nts/bin" -ding=UTF-8 -classpath "/Applications/IntelliJ IDEA 2.app/Contents/plugins/maven/lib/maven3/boot/plexus-classworlds-2.6.0.jar" dehaus.classworlds.Launcher -Didea.version2020.1 package
[INFO] Scanning
[INFO]
[INFO] -----------------< com.naylor:dockerfile-maven-plugin >-----------------
[INFO] Building dockerfile-maven-plugin 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ dockerfile-maven-plugin ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ dockerfile-maven-plugin ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ dockerfile-maven-plugin ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/chenhd/code/DebrisApp_Springboot/debris-app/dockerfile-maven-plugin/src/test/resources [INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ dockerfile-maven-plugin ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ dockerfile-maven-plugin ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests
13:49:50.713 [main] DEBUG st.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.st.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:49:50.735 [main] DEBUG st.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.st.context.support.DefaultBootstrapContext(java.lang.Class,st.context.CacheAwareContextLoaderDelegate)] 13:49:50.762 [main] DEBUG st.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.naylor.doc kerfilemavenplugin.DockerfileMavenPluginApplicationTests] from class [org.st.context.SpringBootTestContextBootstrapper] 13:49:50.781 [main] INFO org.st.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @Cont extHierarchy found for test class [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests], using SpringBootContextLoader 13:49:50.785 [main] DEBUG st.context.support.AbstractContextLoader - Did not detect default resource loca
tion for test cla ss [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests]: class path resource [com/naylor/dockerfilemavenplugin/l] does not exist
13:49:50.785 [main] DEBUG st.context.support.AbstractContextLoader - Did not detect default resource location for test cla ss [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests]: class path resource [com/naylor/dockerfilemavenplugin/vy] does not exist
13:49:50.785 [main] INFO st.context.support.AbstractContextLoader - Could not detect default resource locations for test cl ass [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests]: no resource found for suffixes {-l, vy}. 13:49:50.786 [main] INFO st.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration cl asses for test class [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests]: DockerfileMavenPluginApplicationTests does not d eclare any static, non-private, non-final, nested cla
sses annotated with @Configuration.
13:49:50.826 [main] DEBUG st.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotat ion type [st.context.ActiveProfiles] and class [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests] 13:49:50.926 [main] DEBUG t.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate com ponent class: file [/Users/chenhd/code/DebrisApp_Springboot/debris-app/dockerfile-maven-plugin/target/classes/com/naylor/dockerfilemavenplugin /DockerfileMavenPluginApplication.class]
13:49:50.932 [main] INFO org.st.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.nayl or.dockerfilemavenplugin.DockerfileMavenPluginApplication for test class com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTest s
13:49:51.069 [main] DEBUG org.st.context.SpringBootTestContextBootstrapper - @TestExecutionListeners
is not present f or class [com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicationTests]: using defaults.
13:49:51.070 [main] INFO org.st.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener clas s names from location [META-INF/spring.factories]: [org.kito.MockitoTestExecutionListener, org.springframew kito.ResetMocksTestExecutionListener, org.stdocs.RestDocsTestExecutionListe ner, org.st.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.st.au toconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.st.autoconfigure.web.servlet.WebDriverTe stExecutionListener, org.st.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.st.context.web.ServletTestExecutionListener, st.context.support.DirtiesContextBeforeModesTestExecutionListener, st.context.support.DependencyInjectionTestExecutionListener, st.context.support.DirtiesContextTest ExecutionListener, org.springframework.t
13:49:51.096 [main] DEBUG org.st.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListene r [ansaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/Trans actionAttributeSource]
13:49:51.098 [main] DEBUG org.st.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListene r [st.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make th e default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttri
13:49:51.098 [main] INFO org.st.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.st.context.web.ServletTestExecutionListener@5acf93bb, st.context.support.DirtiesContextBeforeModesTestExe cutionListener@7e7be63f, org.kito.MockitoTestExecutionListener@6cd28fa7, org.st.a utoconfigure.SpringBootDependencyInjectionTestExecutionListener@614ca7df, st.context.support.DirtiesContextTestExecu tionListener@4738a206, st.context.event.EventPublishingTestExecutionListener@66d3eec0, org.st .kito.ResetMocksTestExecutionListener@1e04fa0a, org.stdocs.RestDocsTestExecutionListen er@1af2d44a, org.st.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@18d87d80, org.spring st.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@618425b5, org.st.auto configure.web.servlet.WebDriverTestExecutionListener@58695725, org.st.aut
oconfigure.webservices.client.MockWebServ iceServerTestExecutionListener@543588e6]
13:49:51.114 [main] DEBUG st.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [De faultTestContext@209da20d testClass = DockerfileMavenPluginApplicationTests, testInstance = [null], testMethod = [null], testException = [null], m ergedContextConfiguration = [WebMergedContextConfiguration@e15b7e8 testClass = DockerfileMavenPluginApplicationTests, locations = '{}', clas ses = '{class com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySour ceLocations = '{}', propertySourceProperties = '{org.st.context.SpringBootTestContextBootstrapper=true}', contextCustomiz ers = set[org.st.context.filter.ExcludeFilterContextCustomizer@27ae2fd0, org.st.json.DuplicateJso nObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4278a03f, org.kito.MockitoCont extCustomizer@0, org.st.web.client.TestRestTemplateContextCustomizer@2bbf180e, org.st.auto configure.properties.PropertyMappingContextCustomizer@0, org.s
st.autoconfigure.web.servlet.WebDriverContextCustomiz erFactory$Customizer@96def03, org.st.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextL oader = 'org.st.context.SpringBootContextLoader', parent = [null]], attributes = map['st.context.web. ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
13:49:51.152 [main] DEBUG st.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.abled=false, org.st.context.SpringBootTestContextBootstrapper=true}
.  ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
'  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::        (v2.3.4.RELEASE)
2020-10-12 13:49:51.449  INFO 16693 --- [          main] .d.DockerfileMavenPluginApplicationTests : Starting DockerfileMavenPluginApplicationTest s on neiyo with PID 16693 (started by chenhd in /Users/chenhd/code/DebrisApp_Springboot/debris-app/dockerfile-maven-plugin)
2020-10-12 13:49:51.451  INFO 16693 --- [          main] .d.DockerfileMavenPluginApplicationTests : No active profile set, falling back to default pro files: default
2020-10-12 13:49:52.458  INFO 16693 --- [          main] o.urrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskE xecutor'
2020-10-12 13:49:52.732  INFO 16693 --- [          main] .d.DockerfileMavenPluginApplicationTests : Started DockerfileMavenPluginApplicationTest s in 1.559 seconds (JVM running for 2.86)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.313 s - in com.naylor.dockerfilemavenplugin.DockerfileMavenPluginApplicati onTests
2020-10-12 13:49:53.042  INFO 16693 --- [extShutdownHook] o.urrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applica tionTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:3.2.0:jar (default-jar) @ dockerfile-maven-plugin ---
[INFO] Building jar: /Users/chenhd/code/DebrisApp_Springboot/debris-app/dockerfile-maven-plugin/target/dockerfile-maven-plugin-0.0.1-SNAPSH OT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.3.4.RELEASE:repackage (repackage) @ dockerfile-maven-plugin ---
[INFO] Replacing main artifact with repackaged archive
[INFO]
[INFO] --- dockerfile-maven-plugin:1.3.6:build (default) @ dockerfile-maven-plugin ---
[INFO] Building Docker context /Users/chenhd/code/DebrisApp_Springboot/debris-app/dockerfile-maven-plugin
[INFO]
[INFO] Image will be built as com.naylor/dockerfile-maven-plugin:0.0.1-SNAPSHOT
[INFO]
[INFO] Step 1/5 : FROM java:8
[INFO]
[INFO] Pulling from library/java
[INFO] Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
[INFO] Status: Image is up to date for java:8
[INFO]  ---> d23bdf5b1b1b
[INFO] Step 2/5 : EXPOSE 8080
[INFO]
[INFO]  ---> Using cache
[INFO]  ---> 75767466e0be
[INFO] Step 3/5 : ARG JAR_FILE
[INFO]
[INFO]  ---> Using cache
[INFO]  ---> 2ecdd1234dc2
[INFO] Step 4/5 : ADD target/${JAR_FILE} /app.jar

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。