Graham
Graham

Reputation: 73

Maven + Java application in Dockerfile

I am new to java and maven. I have built an application that executes a flink job. I have created a base docker image but I am not sure how to excecute/run like I run the application in the terminal.

I currently run the application in the terminal as follows:

 mvn package exec:java `-D exec.args="--runner=FlinkRunner --flinkMaster=localhost:8081 --filesToStage=.\target\maven_benchmark-1.0-SNAPSHOT-jar-with-dependencies.jar `" -P flink-runner`

Here is my docker file

FROM maven:latest AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app
RUN mvn -f /usr/src/app/pom.xml clean package

FROM openjdk:14
COPY --from=build /usr/src/app/target/maven_benchmark-1.0-SNAPSHOT-jar-with-dependencies.jar /usr/app/maven_benchmark-1.0-SNAPSHOT-jar-with-dependencies.jar
WORKDIR /usr/app
EXPOSE 8080
ENTRYPOINT ["java","-jar","maven_benchmark-1.0-SNAPSHOT-jar-with-dependencies.jar"]

Any suggestions?

Thanks in advance!

Upvotes: 3

Views: 4354

Answers (1)

Juan Carrey
Juan Carrey

Reputation: 736

You are running your app with a maven plugin and with a maven profile. You need your app to be runnable outside of maven first.

Then, you need to cleanup your docker steps a bit, here are some suggestions:

  • Move copy src after coyping pom and downloading dependencies
  • Do not use root user for runnable image
  • Use slimer base image for runnable image
  • Use exploded jars instead of fat jars to get slimmer layers
  • Make use of .dockerignore to prevent copying unwanted things to the image

Here is a sample Dockerfile:

FROM maven:3.6.3-openjdk-14-slim AS build
WORKDIR /build
# copy just pom.xml (dependencies and dowload them all for offline access later - cache layer)
COPY pom.xml .
RUN mvn dependency:go-offline -B
# copy source files and compile them (.dockerignore should handle what to copy)
COPY . .
RUN mvn package
# Explode fat runnable JARS
ARG DEPENDENCY=/build/target/dependency
RUN mkdir -p ${DEPENDENCY} && (cd ${DEPENDENCY}; jar -xf ../*.jar)


# Runnable image
FROM openjdk:14-alpine as runnable
VOLUME /tmp
VOLUME /logs
ARG DEPENDENCY=/build/target/dependency
# Create User&Group to not run docker images with root user
RUN addgroup -S awesome && adduser -S awesome -G awesome
USER awesome

# Copy libraries & meta-info & classes
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app
# Run application
ENTRYPOINT ["java","-cp","app:app/lib/*","com.myawesomeness.Application"]

Then your app, must be runnable outside of maven first.

Upvotes: 1

Related Questions