1. Introduction
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:
https://github.com/AmirKeshavarz/hello-docker-java
3. Dockerfile
In the root of the project there would be a file named Dockerfile containing below listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# # Step : build and package FROM maven:3.8.1-openjdk-11-slim as BUILD WORKDIR /build COPY pom.xml . RUN mvn dependency:go-offline COPY src/ /build/src/ RUN mvn package # Step : final docker image FROM openjdk:11-jre-slim EXPOSE 8080 COPY --from=BUILD /build/target /opt/target #COPY --from=BUILD /build/myjre /usr/local/openjdk-11 WORKDIR /opt/target 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:
1 |
sudo docker build -t hello . |
1 |
sudo docker run -dit hello -p 8080:8080 |
1 2 3 4 5 |
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 |
5. Next
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.