FROM maven:3.9.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY ./pom.xml ./
RUN mvn dependency:resolve
COPY . .
RUN mvn clean install -DskipTests

#FROM openjdk:21-jdk-slim
FROM eclipse-temurin:21-jre-jammy

# Create a non-root user and group for security
RUN groupadd -r appgroup && useradd -r -s /bin/false -g appgroup appuser

# Create a directory for heap dumps and give ownership to the new user
RUN mkdir /dumps && chown appuser:appgroup /dumps

# Set the working directory
WORKDIR /app

# Copy the application jar from the build stage
COPY --from=build /app/target/*.jar app.jar

# Change ownership of the application files to the non-root user
RUN chown appuser:appgroup app.jar

# Switch to the non-root user
USER appuser

# Run the jar file with JVM flags for heap dump generation on OutOfMemoryError
ENTRYPOINT ["java", "-XX:+HeapDumpOnOutOfMemoryError", "-XX:HeapDumpPath=/dumps/heap.hprof", "-jar", "app.jar"]
