首頁  >  文章  >  Java  >  使用 GraalVM 建構器從 Spring Boot 應用程式建立本機映像

使用 GraalVM 建構器從 Spring Boot 應用程式建立本機映像

WBOY
WBOY原創
2024-08-05 20:04:50670瀏覽

Build native image from Spring Boot Application with GraalVM builder

概述

本節介紹如何使用 GraalVM 的本機映像產生器從 Spring Boot 應用程式建立本機映像,以及如何在 Docker 容器中執行此本機映像。

客觀的

在軟體架構和微服務架構設計中,我們必須考慮應用程式的可擴展性、效能。每當應用程式中的請求數量增加時,我們的應用程式應該開始快速擴展並有效地利用資源。

我正在考慮使用 Spring Boot 提前 (AOT) 編譯與 GraalVM 以及 Java 虛擬線程(在 JDK 21 及更高版本中可用)在容器中運行可執行檔。

  • AOT 編譯對於快速啟動時間和可預測效能很重要的場景是有利的,但代價是運行時適應性較差。
  • 與虛擬機器 (VM) 相比,容器是輕量級的,使用的資源較少,因為它們共用主機作業系統核心。容器的啟動和停止速度比虛擬機器快得多,從而實現更快的擴展和部署。
  • 虛擬執行緒可以提高處理大量並發任務的應用程式的效能。這對於 Web 伺服器、資料庫和其他 I/O 密集型系統等應用程式尤其有利。虛擬線程比傳統線程使用更少的資源。它們由運行時以最小化記憶體使用和 CPU 開銷的方式進行管理。

在這個架構設計決策中,我們獲得了好處,但也必須考慮以下實施挑戰和設計注意事項:

  • 虛擬執行緒:如果我們的業務邏輯是CPU密集的,例如需要大量記憶體運算的場景,我們應該避免使用虛擬執行緒。
  • 提前 (AOT) 編譯:AOT 編譯器可能無法正確處理反射、代理編碼或序列化。此外,GraalVM 是一項相對較新的技術,對從 Spring Boot 應用程式建立本機映像提出了挑戰,並導致建置時間增加。
  • 容器:容器提供了許多好處,但也帶來了一些與安全、網路、效能、CI/CD 等領域相關的挑戰。一些示例是
    • 容器可能包含來自基礎鏡像或依賴項的漏洞。
    • 將容器整合到現有的 CI/CD 管道中可能具有挑戰性,需要更改建置、測試和部署流程。
    • 管理 Kubernetes 等容器編排平台可能很複雜,並且需要專業知識。
    • 有效地擴展和縮減容器以處理不同的負載,而不會過度配置或配置不足的資源。

Spring Boot 應用
為了測試這個用例,我正在建立一個 Spring Boot 應用程序,該應用程式在「/hello」處公開 REST 端點。我正在使用以下配置、庫和工具:

  • 有 REST 的 Spring Boot 3.2.8
  • Spring Boot AOT 編譯
  • Spring Boot GraalVM 原生鏡像
  • Maven 3.9.8 建置工具
  • Java 22

我們需要在 POM XML 檔案中新增以下配置。

Spring Boot 屬性配置

<properties>
    <java.version>22</java.version>
    <spring-native.version>0.12.1</spring-native.version>
</properties>

Spring Boot AOT 外掛程式配置

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
       <execution>
          <id>process-aot</id>
          <goals>
             <goal>process-aot</goal>
          </goals>
       </execution>
    </executions>
</plugin>

GraalVM 外掛程式配置

<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
    <configuration>
       <imageName>app-native-binary</imageName>
       <metadataRepository>
          <enabled>true</enabled>
       </metadataRepository>
       <buildArgs>
          <buildArg>--static --libc=musl</buildArg>
          <buildArg>-H:+ReportExceptionStackTraces</buildArg>
       </buildArgs>
       <mainClass>com.developerhelperhub.tutorial.springboot.tutorial.TutorialStartupPerformanceApplication</mainClass>
    </configuration>
    <executions>
       <execution>
          <id>add-reachability-metadata</id>
          <goals>
             <goal>add-reachability-metadata</goal>
          </goals>
       </execution>
    </executions>
</plugin>
  • 「mainClass」:設定Spring Boot應用程式的郵件類別
  • "imageName": 設定原生鏡像名稱
  • “buildArgs”:配置 —libc=”msul”,我們正在配置 GraalVM 以使用“libc musl”相容庫構建本機映像,因為我們將在 Alpine Linux 機器上運行此映像。與其他標準函式庫相比,Musl 的設計較小,使用的記憶體較少,非常適合資源受限的環境。

建置二進位檔案並建立 Docker 映像

我們需要為特定作業系統主機和 CPU 架構建立本機映像,本機映像將在容器中運作。

我們使用 Alpine Linux 來在容器中運行我們的應用程序,因為它體積小、簡單且安全。為了實現這一點,我們需要使用適當的 GraalVM 配置來建立我們的應用程式。 Alpine 的系統需求是作業系統和 CPU 架構。

  • 「架構」:「amd64」
  • 「作業系統」:「linux」
  • C 通用函式庫:「libc musl」

以下指令我們可以用來檢查「amd64/alpine」影像

docker pull amd64/alpine # pull the image

docker image inspect amd64/alpine # inspect the image

We can use docker container to build the native image instead of setup the GraalVM and Java related configuration in our locally. I am using “ghcr.io/graalvm/native-image-community:22-muslib” docker image to build the native.

Following command we can use to inspect the “ghcr.io/graalvm/native-image-community:22-muslib” image

docker pull ghcr.io/graalvm/native-image-community:22-muslib # pull the image

docker image inspect ghcr.io/graalvm/native-image-community:22-muslib # inspect the image

I am creating a build image to test and debug the container, ensuring that all configurations and services are installed correctly. This approach will help us quickly identify and resolve any issues.

Following steps are added in the docker file, the file name “DockerfileBuild”

FROM ghcr.io/graalvm/native-image-community:22-muslib as build

# Install necessary tools
RUN microdnf install wget 
RUN microdnf install xz

# Install maven for build the spring boot application
RUN wget https://dlcdn.apache.org/maven/maven-3/3.9.8/binaries/apache-maven-3.9.8-bin.tar.gz
RUN tar xvf apache-maven-3.9.8-bin.tar.gz

# Set up the environment variables needed to run the Maven command.
ENV M2_HOME=/app/apache-maven-3.9.8
ENV M2=$M2_HOME/bin
ENV PATH=$M2:$PATH

# Install UPX (Ultimate Packer for eXecutables) to compress the executable binary and reduce its size.
RUN wget https://github.com/upx/upx/releases/download/v4.2.4/upx-4.2.4-amd64_linux.tar.xz
RUN tar xvf upx-4.2.4-amd64_linux.tar.xz

# Set up the environment variables required to run the UPX command.
ENV UPX_HOME=/app/upx-4.2.4-amd64_linux
ENV PATH=$UPX_HOME:$PATH

#Copy the spring boot source code into container
RUN mkdir -p /app/spring-boot-rest-api-app
COPY spring-boot-rest-api-app /app/spring-boot-rest-api-app

#Compile the native image
RUN cd /app/spring-boot-rest-api-app && mvn -Pnative native:compile

#Compressed binary file
RUN upx -7 -k /app/spring-boot-rest-api-app/target/app-native-binary
WORKDIR /app
ENTRYPOINT ["/bin/bash"]

I am using the UPX compression tool in the build process to reduce the image size, UPX will typically reduce the file size of programs and DLLs by around 50%-70%, thus reducing disk space, network load times, download times and other distribution and storage costs.

Use the following command to build the Docker image.

docker build --no-cache -f DockerfileBuild -t alpine-graalvm-build .

After the build is complete, the image size will be 1.85 GB.

REPOSITORY                               TAG         IMAGE ID       CREATED          SIZE
alpine-graalvm-build                     latest      81d23bc1bc99   36 seconds ago   1.85GB

We can verify the configuration and installation within the container before creating a smaller container inside the Alpine Linux box. The following command will allow us to enter the container:

docker run --rm -it --entrypoint /bin/bash alpine-graalvm-build

java --version #verify the java version
mvn --version #verify the maven version
upx --version #verify the upx version

ls /app/spring-boot-rest-api-app/target/app-native-binary #verify the binary available

/app/spring-boot-rest-api-app/target/app-native-binary #run the executable

We know that this native image includes all the dependencies necessary to run the binary standalone, without requiring any build-related tools such as GraalVM, Maven, UPX, or source code. We can use a Docker multi-stage build approach to copy the build file into our application image. By using multiple stages, you can separate the build environment from the runtime environment. This means only the necessary artifacts are included in the final image, significantly reducing its size.

Following steps are added in the docker file, the file name “DockerfileBuildAndCreateAlpineContainer”

FROM ghcr.io/graalvm/native-image-community:22-muslib as build

# Install necessary tools
RUN microdnf install wget 
RUN microdnf install xz

# Install maven for build the spring boot application
RUN wget https://dlcdn.apache.org/maven/maven-3/3.9.8/binaries/apache-maven-3.9.8-bin.tar.gz
RUN tar xvf apache-maven-3.9.8-bin.tar.gz

# Set up the environment variables needed to run the Maven command.
ENV M2_HOME=/app/apache-maven-3.9.8
ENV M2=$M2_HOME/bin
ENV PATH=$M2:$PATH

# Install UPX (Ultimate Packer for eXecutables) to compress the executable binary and reduce its size.
RUN wget https://github.com/upx/upx/releases/download/v4.2.4/upx-4.2.4-amd64_linux.tar.xz
RUN tar xvf upx-4.2.4-amd64_linux.tar.xz

# Set up the environment variables required to run the UPX command.
ENV UPX_HOME=/app/upx-4.2.4-amd64_linux
ENV PATH=$UPX_HOME:$PATH

#Copy the spring boot source code into container
RUN mkdir -p /app/spring-boot-rest-api-app
COPY spring-boot-rest-api-app /app/spring-boot-rest-api-app

#Compile the native image
RUN cd /app/spring-boot-rest-api-app && mvn -Pnative native:compile

#Compressed binary file
RUN upx -7 -k /app/spring-boot-rest-api-app/target/app-native-binary
WORKDIR /app

#Second stage: Create the runtime image
FROM amd64/alpine

#Set the working directory
WORKDIR /app

#Copy the built application from the first stage
COPY --from=build /app/spring-boot-rest-api-app/target/app-native-binary .

#Expose port which our spring boot application is running
EXPOSE 8080 

#Command to run the application
ENTRYPOINT ["/app/app-native-binary"]

Use the following command to build the Docker image.

docker build -f DockerfileBuildAndCreateAlpineContainer -t alpine-graalvm .

After the build is complete, the image size of container will be 32.8MB.

REPOSITORY                               TAG         IMAGE ID       CREATED          SIZE
alpine-graalvm                           latest      79676c696920   11 seconds ago      32.8MB

We can verify the container.

docker run --rm -it --entrypoint sh alpine-graalvm

ls /app #verify the binary available

/app/app-native-binary #run the executable

The application startup time is just 0.074 seconds, whereas a typical Spring Boot application running on the JVM has a startup time of approximately 1.665 seconds.

Started TutorialStartupPerformanceApplication in 0.074 seconds (process running for 0.075)

Following command can be use to run the docker container for running the application

docker run -d --name test-app -p 8080:8080 alpine-graalvm #run the container

curl http://localhost:8080/hello # checking the endpoints

Spring boot and GraalVM references

  • Spring Boot Introduction GraalVM Native Images
  • GraalVM documentation build Spring Boot Native Executable
  • GraalVM Maven Plugin Documentation
  • Sample Spring Boot Application Docker Image Setup with GraalVM
  • Sample Native Images with Spring Boot and GraalVM
  • Spring Boot 3.2.8 GraalVM Native Images Documentation
  • Spring Boot GraalVM UPX Tutorial Video
  • Spring Boot Alpine Linux Docker Native Image Example ## Docker and GraalVM References
  • GraalVM Containers Images
  • Docker Environment Variables
  • Maven Download
  • UPX Documentation
  • UPX Releases
  • Docker Stop Container

Source Code

  • Spring Boot Github Repo
  • Kubernetes Related Repo

以上是使用 GraalVM 建構器從 Spring Boot 應用程式建立本機映像的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn