1. Story
- As a Java developer I want to build a Docker image
- I want to aquire a Docker feature named multi-stage builds
- While that process I want to prevent downloading mvn dependecies through building docker image process
- So I want to manually inject dependencies into Docker image
2. Build Docker image
-
- Sample project:
-
- Create local Maven repo:
1 2 |
# mvn dependency:go-offline -Dmaven.repo.local=./repo package # tar cf repo.tar.gz ./repo |
-
- Create Dockerfile:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Step : build and package FROM maven:3.6-openjdk-17-slim as BUILD ADD repo.tar.gz /usr/share/maven/ref/ COPY . /usr/src/app WORKDIR /usr/src/app RUN mvn dependency:go-offline package # Step : final docker image FROM openjdk:17-jdk-alpine EXPOSE 8080 COPY --from=BUILD /usr/src/app/target /opt/target WORKDIR /opt/target CMD ["java", "jar", "hello.jar"] |
-
- Build docker image:
1 |
# docker build -f Dockerfile-injectrepo -t mytutorial/hello . |
1 |
# docker run mytutorial/hello -p 8080:8080 |
- Go to browser and browse into http:\localhost:8080
3. Related subjects
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.