How to reduce docker Image?
Kashif Mehmood
Terraform Certified | Kubernetes Certified Administrator | Kubernetes Application Developer| AWS Solution Architect | Cloud Infrastructure (AWS ,GCP) and on-premises
Docker is an open-source platform that enables developers to build, package, and deploy applications as containerized environments. Docker containers are lightweight, portable, and self-contained, allowing applications to run consistently across different computing environments, from development to production.
Docker has become an essential tool for modern software development, as it helps streamline the deployment process, reduces infrastructure costs, and improves the reliability and scalability of applications.
one of the biggest problem is docker is image size. we can use followings methods to reduce docker image size
USING SMALL BASE IMAGE
We have a docker file with alpine base image. It has image size 39.9MB only
FROM alpine:3.14
RUN apk add --no-cache mysql-client
ENTRYPOINT ["mysql"]
when we used ubuntu as base image The final image size become 154MB
FROM ubuntu:20.04
RUN apt-get update \
&& apt-get install -y --no-install-recommends mysql-client \
&& rm -rf /var/lib/apt/lists/*
ENTRYPOINT ["mysql"]
Minimize the number of layers
we installed packages in different line in dockerfile using RUN it which will create different layers. we got images size 68.4MB
领英推荐
FROM alpine:3.14
RUN apk add --no-cache mysql-client
RUN apk add nano
RUN apk add vim
RUN apk add net-tools
RUN apk add nginx
RUN echo "I am Testing the image"
ENTRYPOINT ["mysql"]
when we combine package installation using RUN in single line in dockerfile It will create single layer for this RUN we got images size 68.2MB
FROM alpine:3.14
RUN apk add --no-cache mysql-client nano vim net-tools nginx
RUN echo "I am Testing the image"
ENTRYPOINT ["mysql"]
USING Multistage build
when we use normal dockerfile. we got image size of 1.05GB
FROM maven:3.8.5-openjdk-1
WORKDIR /app
COPY . /app
RUN mvn clean install -DskipTests
EXPOSE 9091
CMD ["java","-Dlog4j2.formatMsgNoLookups=true","-jar","/app/target/revalu2-email-service-0.0.1-SNAPSHOT.jar"]
When we use multistage build. We got final image size 538MB. which is almost 50% less in size
FROM maven:3.8.5-openjdk-17? AS builde
WORKDIR /app
COPY . /app
RUN mvn clean install -DskipTests
FROM openjdk:17.0.2-jdk
WORKDIR /root/
RUN mkdir ReportPath
COPY --from=builder /app/target/revalu2-email-service-0.0.1-SNAPSHOT.jar .
EXPOSE 9091
CMD ["java","-Dlog4j2.formatMsgNoLookups=true","-jar","/root/revalu2-email-service-0.0.1-SNAPSHOT.jar"]
Great post! Thanks for sharing your tips on reducing docker image size. Being mindful of the layers and base images used can make a big difference when it comes to optimizing Docker containers.