In this exercise, you will focus on optimizing a Docker image by minimizing its size. Using the Dockerfile from the previous exercise, "Containerizing a Legacy Application," you will learn how to reduce the image size while ensuring that the application still runs correctly. This optimization is crucial for faster deployments, lower storage requirements, and improved performance.
The original Docker image created in the previous exercise is approximately 800 MB in size. In this exercise, your goal is to significantly reduce this size.
Starting from the Dockerfile created in the previous exercise, you need to modify it to reduce the image size. The goal is to eliminate unnecessary layers and dependencies while maintaining the functionality of the Dockerized application.
To successfully complete this exercise, you need to:
https://github.com/tdevsin/docker-mastery.git
eclipse-temurin:21-jre
, which includes only the JRE (Java Runtime Environment) instead of the full JDK (Java Development Kit). This will significantly reduce the image size. Research around smaller images.Make sure you’ve tried your best before looking at the solution.
To optimize the Dockerfile, we'll use multi-stage builds. The first stage will build the application, and the second stage will create a minimal runtime image:
# Stage 1: Build the application
FROM maven:3.9.9-eclipse-temurin-21 AS build
# Copy the project
COPY . /app
# Change the working directory
WORKDIR /app
# Build the project
RUN mvn clean package
# Stage 2: Create a minimal runtime image
# alpine images are generally known for small sizes.
FROM eclipse-temurin:21-jre-alpine
# Copy the built jar from the first stage
COPY /app/target/dockermastery-0.0.1-SNAPSHOT.jar /app/dockermastery.jar
# Set the working directory
WORKDIR /app
# Expose application PORT
EXPOSE 8080
# Launch the jar
ENTRYPOINT ["java", "-jar", "dockermastery.jar"]
eclipse-temurin:21-jre-alpine
), which contains only the necessary runtime environment.eclipse-temurin:21-jre-alpine
, we remove the need for the full JDK, which is unnecessary for running the application.To build the optimized Docker image, run the following command:
docker build -t todoapp-minimal .
This will build the Docker image using the optimized Dockerfile.
Now that the optimized image is ready, you can run the container using the following command:
sudo docker run -it -p 8080:8080 --network=todo -e DB_URL=jdbc:mysql://tododb:3306/dockermastery -e DB_USERNAME=root -e DB_PASSWORD=root todoapp-minimal
Open your browser and go to http://localhost:8080/
. This should return the sample todo list in JSON
format.
Congratulations! You’ve successfully optimized the Docker image for your legacy application, potentially reducing the image size from 800 MB to under 300 MB. If you found this exercise challenging, don't worry. Optimization is a key skill in Docker, and we will explore more advanced techniques in upcoming exercises.