How to Shrink Docker Images: Reduce a 743 MB Java Image to 536 MB
This tutorial demonstrates step‑by‑step techniques—using ADD, combining commands in a single layer, and leveraging .dockerignore—to dramatically reduce the size of a Java Docker image from 743 MB down to 536 MB while keeping functionality intact.
1. Introduction
We want Docker images as small as possible; this article shows how to reduce a simple Java image from 743 MB to 536 MB.
2. Example
Goal
Build a Java image based on a CentOS base and a downloaded jdk-8u101-linux-x64.tar.gz.
Process
1) First version
Dockerfile content:
FROM centos
COPY jdk-8u101-linux-x64.tar.gz /usr/local/
WORKDIR /usr/local
RUN tar -zxf /usr/local/jdk-8u101-linux-x64.tar.gz && rm /usr/local/jdk-8u101-linux-x64.tar.gz
ENV JAVA_HOME /usr/local/jdk1.8.0_101
ENV PATH $JAVA_HOME/bin:$PATHResulting image size: 743 MB . The problem is that the COPY and RUN are in separate layers, so the tar file remains in the image.
2) Second version
Use ADD to unpack directly:
FROM centos
ADD jdk-8u101-linux-x64.tar.gz /usr/local/
ENV JAVA_HOME /usr/local/jdk1.8.0_101
ENV PATH $JAVA_HOME/bin:$PATHImage size: 562 MB . If the archive must be downloaded, combine download, extract, and delete in one RUN layer:
RUN wget http://xxx.com/app && tar -xzf app.tar.gz && rm app.tar.gz3) Third version
Further reduce by removing unnecessary files with a .dockerignore file.
Dockerfile:
FROM centos
COPY jdk1.8.0_101 /usr/local/jdk1.8.0_101
ENV JAVA_HOME /usr/local/jdk1.8.0_101
ENV PATH $JAVA_HOME/bin:$PATH.dockerignore: */*.zip Directory layout:
├── .dockerignore
├── Dockerfile
└── jdk-8u101-linux-x64.tar.gzFinal image size: 536 MB , a reduction of 207 MB . .dockerignore can also exclude docs, .git, .svn, tmp, etc.
3. Summary
The optimization principle is to put as little as possible into the image and choose the smallest suitable base image, such as Alpine (≈5 MB) instead of larger CentOS or Ubuntu images, or create custom base images tailored to each service.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
