Video in progress
What problems do you see in this Dockerfile?
FROM maven:latest
COPY . /app
WORKDIR /app
RUN mvn package
ENV DB_PASSWORD=prod123
CMD java -jar target/shop-api-1.0.jar
The image still contains the JDK and Maven, latest is used, the cache does not work because the code is copied before the dependencies, and the app runs as root in shell form.
📖 Answer
Line by line:
maven:latest: the version is vague, and tomorrow the Java version may change. The final image keeps Maven, the JDK and the~/.m2cache, hundreds of megabytes of stuff you do not need.COPY . /appbefore the dependencies: on every code change everything is downloaded again. Without a.dockerignore,.gitgoes inside too.RUN mvn packageruns the tests as well. That is not bad in itself, but if the tests need Docker (as Testcontainers does), the build fails.ENV DB_PASSWORD=prod123: the most serious one. The password stays in the image metadata, and anyone can see it withdocker historyordocker inspect.CMDin shell form: SIGTERM never reaches Java.- No
USER: it runs as root.
The fixed version:
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn -B dependency:go-offline
COPY src ./src
RUN mvn -B package -DskipTests
FROM eclipse-temurin:21-jre
RUN useradd --system app
WORKDIR /app
COPY --from=build /src/target/*.jar app.jar
USER app
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
And the password arrives at run time through a Secret.
Sign up to mark studied questions and save your progress.