Dockerizing a Java
Now there are two ways this can be done,
1) Copy only the Jar file
this is the more Viable solution as it also keeps less files in the image
FROM openjdk:20-jdk
EXPOSE 8080
ARG JAR\_FILE=target/\*.jar
COPY ${JAR\_FILE} app.jar
ENTRYPOINT \["java", "-jar", "/app.jar"\]
Here's the walk through
-
Set the base image to openJDK
-
expose port 8080
-
Create a variable called JAR_FILE,
-
copy JAR_FILE from the root and rename it to app.jar, IE the command looks like so:
COPY target/*.jar app.jar
-
Run app.jar once the Image is run
Here's what the folders look like (simplified)
|-src
|-target
|--build.jar
|-pom.xml
|-dockerfile
2) Copy Entire project
Here's what that'll look like for a spring boot app
FROM openjdk:20-jdk
EXPOSE 8080
COPY . /app
WORKDIR /app
RUN MVN INSTALL
RUN MVN BUILD
ENTRYPOINT \["MVN", "springboot:run"\]
Basically we:
-
Set base image to openJDK
-
expose 8080
-
copy everything to /app
-
set our work DIR to /app
-
run maven install
-
run maven build
-
and set our entry point to mvn springboot:run
Finally we can build and run it like so
docker build -t imagename .
docker run imagename