使用dockerfile插件打包微服務(wù)鏡像

概述

使用spotify的dockerfile maven插件,可以幫助我們將maven與docker進行集成,更快速的在maven構(gòu)建過程中進行docker鏡像的打包操作。
配置仍然是基于Dockerfile的,插件只是輔助。

請注意,插件的名稱是 spotifydockerfile-maven-plugin ,而非 docker-maven-plugin

詳情可訪問 github頁面

準(zhǔn)備工作

首先準(zhǔn)備一個spring-boot工程,假設(shè)工程名為playground。另外本機需要安裝docker,過程都不再贅述。
本文平臺為macOS12,docker在不同平臺下可能有所差異。

由于dockerhub訪問較慢,可以用$$先自行搭建一個socks5代理來加速訪問。代理不是必須的。

export ALL_PROXY=socks5://xx.xx.xx.xx:xx

建立Dockerfile

在工程目錄下新建一個Dockerfile,基于openjdk的鏡像:

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD target/playground-1.1.0.jar app.jar
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

使用docker命令構(gòu)建鏡像

在使用Maven插件之前,可以試著先用docker命令來進行打包:

docker build -t="yourname/playground:latest" .

查看鏡像是否生成:

docker images

然后可以使用docker push推送鏡像:

docker push yourname/playground

編輯pom.xml

測試通過后,就可以在pom.xml中添加spotify插件了

<properties>
   <docker.image.prefix>yourname</docker.image.prefix>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>dockerfile-maven-plugin</artifactId>
            <version>1.3.4</version>
            <configuration>
                <repository>${docker.image.prefix}/${project.artifactId}</repository>
            </configuration>
        </plugin>
    </plugins>
</build>

另外還可以添加一個execution,在maven的install生命周期自動進行build和push。

<executions>
    <execution>
        <id>default</id>
        <phase>install</phase>
        <goals>
            <goal>build</goal>
            <goal>push</goal>
        </goals>
    </execution>
</executions>

使用插件構(gòu)建鏡像

mvn install dockerfile:build

使用插件推送鏡像

在使用dockerfile-maven-plugin推送前,需要先編輯一下~/.docker/config.json,添加用戶名及密碼,否則會報認證失敗。

{
  "auths": {
    "https://index.docker.io/v1/": {
      "Username": "xxxxxx",
      "Secret": "xxxxxx"
    }
  },
  "credsStore": "osxkeychain"
}

然后直接運行即可:

mvn dockerfile:push

運行鏡像

最后,可以使用docker run命令可以將鏡像啟動,在瀏覽器中查看一下運行情況

docker run -p 8080:8080 -t yourname/playground

使用docker logs簡單查看日志

docker ps
docker logs f4d7e737f47f
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容