As a Java developer I want to build a lean Docker image for my java app. A Docker feature named "multi-stage builds" make this process so easy and straight forward.
2. Sample Project
As a simple sample project we have a Spring-Boot hello world project which responses on http://localhost:8080
You can provide your desired project or clone/download the github repository from here:
3. DockerfileIn the root of the project there would be a file named Dockerfile containing below listing:
# Step : build and package
FROM maven:3.8.1-openjdk-11-slim as BUILD
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src/ /build/src/
RUN mvn package
# Step : final docker image
COPY --from=BUILD /build/target /opt/target
#COPY --from=BUILD /build/myjre /usr/local/openjdk-11
CMD ["java", "-jar", "hellojavadocker.jar"]
4. How to run
- Docker must be installed on your system
- In terminal go to root of the project and run below command for building docker image:
- In terminal run below commands for running the container:
- Check your application in browser: Go to browser and browse into http:\\localhost:8080
- Check your docker container: Go to terminal and run below command:
sudo docker build -t hello .
sudo docker run -dit hello -p 8080:8080
sudo docker ps
--- output ---
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b0c3ecbeafc0 amir/hello "java -jar hellojava…" 15 seconds ago Up 10 seconds 0.0.0.0:8080->8080/tcp intelligent_vaughan
Below, a couple of points are mentioned which are not described here to keep this article simple.
- Use -v option of docker for mounting your local maven repository and prevent downloading maven dependencies in build repetitive phase.
- Use Maven plugins for building images instead of direct docker CLI commands.
- Push docker image into a docker hub to make it accessible from hosts outer of your local.