Maven插件创建并运行Docker镜像

环境

linux上的测试环境,安装docker服务;win10开发环境,未装docker,保证网络能连接到测试环境的Docker即可。

一、开启远程访问

开启Docker的远程访问,使本地win10构建好的镜像,通过maven插件可自动添加到linux的docker中。

cat /usr/lib/systemd/system/docker.service

二、pom添加maven插件

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <docker.image.prefix>springboot</docker.image.prefix>
</properties>
<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.13</version>
    <configuration>
        <!-- 镜像地址 -->
        <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
	<!-- docker的DockerFile配置文件路径 -->
	<dockerDirectory>src/main/docker</dockerDirectory>
	<!-- 远程docker容器的地址 -->
	<dockerHost>http://10.1.4.17:2375</dockerHost>
	<resources>
	    <resource>
		<targetPath>/</targetPath>
		<directory>${project.build.directory}</directory>
		<include>${project.build.finalName}.jar</include>
	    </resource>
	    <resource>
	        <targetPath>/htmlRepo</targetPath>
				<directory>${project.build.testOutputDirectory}/cis_branchReport</directory>
		<include>**/*.html</include>
	    </resource>
	    <resource>
		<targetPath>/htmlRepo</targetPath>
				<directory>${project.build.testOutputDirectory}/cis_dvc</directory>
		<include>**/*.html</include>
	    </resource>
	    <resource>
		<targetPath>/htmlRepo</targetPath>
				<directory>${project.build.testOutputDirectory}/cis_map4room</directory>
		<include>**/*.html</include>
	    </resource>
	    <resource>
		<targetPath>/pyRepo</targetPath>
		<directory>${project.build.outputDirectory}/static/assets/pythons</directory>
		<include>**/*</include>
	    </resource>
	</resources>
    </configuration>
</plugin>

注意:在pom中不可使用<expose><entryPoint>的原因(即要么都通过Dockerfile构建,要么都在pom中构建):

三、新建Dockerfile文件

在项目src/main/docker下新建Dockerfile文件:

# 基于哪个镜像
FROM java:8
# 将本地文件夹挂载到当前容器(将容器中的目录当做持久化存储)
VOLUME /tmp
# 复制文件到容器,也可以直接写成 ADD cis-1.0.0.jar /cis.jar
ADD cis-1.0.0.jar cis.jar
RUN bash -c 'touch /cis.jar'
# 声明需要暴露的端口
EXPOSE 8761
# 配置容器启动后执行的命令
ENTRYPOINT ["java", "-jar", "/cis.jar", "--spring.profiles.active=test", "--server.port=8761"]

四、项目根目录下打包

E:\codes_svn\cis_trunk>mvn -DskipTests=true clean package docker:build
或E:\codes_svn\cis_trunk>mvn -DskipTests=true clean install docker:build

五、去docker服务器上查看镜像情况

docker images

发现已多了一个镜像:

六、运行镜像以启动一个容器

docker run -d -p 8760:8761 springboot/cis

然后在本地访问服务:

借此,也可在Jenkins上通过修改Execute Shell,来使测试环境容器化。

发布了62 篇原创文章 · 获赞 22 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/songzehao/article/details/103366872