构建最小JDK Docker镜像

一、问题描述

最近在使用docker部署spring Cloud微服务项目的时候发现,每个服务构建出的镜像文件高达700M。
镜像较大的镜像往往会导致移植,迁移缓慢。最后启动并进入容器发现,jdk用的是openjdk,那么我们就需要在构建镜像时使用更小的jdk作为基础镜像,进而减小镜像的大小.

二、解决方案

使用Oracle的JRE而不是openjdk,并构建成Docker镜像。

2.1 下载并上传jre到linux服务器

jre8下载地址:https://www.java.com/en/download/manual.jsp

jre linux x64

大小大概是80M

2.2 删除无用文件

解压压缩包

$ tar -xvcf jre-8u181-linux-x64.tar.gz

删除无用的文件

$ cd jre1.8.0_181/
$ rm -rf COPYRIGHT LICENSE README release THIRDPARTYLICENSEREADME-JAVAFX.txt THIRDPARTYLICENSEREADME.txt Welcome.html
$ rm -rf   lib/plugin.jar            lib/ext/jfxrt.jar            bin/javaws            lib/javaws.jar            lib/desktop            plugin            lib/deploy*            lib/*javafx*            lib/*jfx*            lib/amd64/libdecora_sse.so            lib/amd64/libprism_*.so            lib/amd64/libfxplugins.so            lib/amd64/libglass.so            lib/amd64/libgstreamer-lite.so            lib/amd64/libjavafx*.so            lib/amd64/libjfx*.so
重新打包
$ tar zcvf jre1.8.0_231.tar.gz *

2.3 新建Dockerfile

vim Dockerfile_jre1.8.0_231

# using alpine-glibc instead of alpine  is mainly because JDK relies on glibc
FROM docker.io/jeanblanchard/alpine-glibc:latest
# author
MAINTAINER sandu <>
# date zone 设置时间,避免相差8个小时
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo "Asia/Shanghai" > /etc/timezone
# A streamlined jre
ADD jre1.8.0_231.tar.gz /usr/local/java/jdk/
# set env
ENV JAVA_HOME /usr/local/java/jdk/
ENV PATH ${PATH}:${JAVA_HOME}/bin
# run container with base path:/opt
WORKDIR /opt

2.4 构建docker镜像

docker build -t 192.168.75.12/library/jre:1.8 -f Dockerfile_jre1.8.0_231 .

这样构建的jdk镜像大概是130M左右。

2.5 测试

# docker run -it 192.168.75.12/library/jre:1.8
/opt # java -version
java version "1.8.0_231"
Java(TM) SE Runtime Environment (build 1.8.0_231-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)
/opt # date
Tue Oct 29 10:22:33 UTC 2019

2.6 推送到Harbor仓库

[ jre1.8.0_231]# docker login http://192.168.75.12
Authenticating with existing credentials...
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

[ jre1.8.0_231]# docker push 192.168.75.12/library/jre:1.8
The push refers to repository [192.168.75.12/library/jre]
0c64e8821df0: Pushed 
cc24d9491ad4: Pushed 
fd414845c3cc: Pushed 
6dbecb8e1a3e: Layer already exists 
77cae8ab23bf: Layer already exists 
1.8: digest: sha256:3484a7852d1330867c14805c03db28ccde2cc327e2ceb5658aaeb0bea010122a size: 1365

相关推荐