Dockerfile Examples

Organize Dockerfile examples here.

Spring boot application

Version 1: Using JAR file

Create a demo project from Spring Initializr

Building the Java project

# set the version of JDK to 21 by the sdk command (optional)
$ sdk use java 21.0.3-zulu
# build the project
$ ./gradlew build -x test

Dockerfile

FROM eclipse-temurin:21-jre-alpine

ENV TZ=Asia/Shanghai
# The JAR_FILE argument can be overriden by --build-arg
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

Building Docker image and running Docker container

docker build --build-arg JAR_FILE=build/libs/\*.jar -t my-spring-boot-app .
docker run -p 8080:8080 my-spring-boot-app

Version 2: Separating dependencies and application resources in a Spring Boot fat JAR file to improve performance

Create a demo project from Spring Initializr

Building the Java project

# set the version of JDK to 21 by the sdk command (optional)
$ sdk use java 21.0.3-zulu
# build the project
$ ./gradlew build -x test
# Note: change demo-0.0.1-SNAPSHOT.jar to your project jar file name
$ rm -rf build/dependency/ && mkdir -p build/dependency && (cd build/dependency; jar -xf ../libs/demo-0.0.1-SNAPSHOT.jar)

Dockerfile

FROM eclipse-temurin:21-jre-alpine

ENV TZ=Asia/Shanghai
ARG DEPENDENCY=build/dependency
COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY ${DEPENDENCY}/META-INF /app/META-INF
COPY ${DEPENDENCY}/BOOT-INF/classes /app
# Note change the main class path com.example.demo.DemoApplication to your project main class
ENTRYPOINT ["java","-cp","app:app/lib/*","com.example.demo.DemoApplication"]

Building Docker image and running Docker container

docker build -t my-spring-boot-app .
docker run -p 8080:8080 my-spring-boot-app

React application

Dockerfile

# Build Stage  
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Production Stage
FROM nginx:stable-alpine AS production
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Building Docker image and running Docker container

docker build -t my-react-app .
docker run my-react-app