検索
ホームページJava&#&チュートリアルGraalVM ビルダーを使用して Spring Boot アプリケーションからネイティブ イメージをビルドする

Build native image from Spring Boot Application with GraalVM builder

概要

このセクションでは、GraalVM のネイティブ イメージ ビルダーを使用して Spring Boot アプリケーションからネイティブ イメージを作成する方法と、このネイティブ イメージを Docker コンテナーで実行する方法について説明します。

客観的

ソフトウェア アーキテクチャとマイクロサービス アーキテクチャの設計では、アプリケーションのスケーラビリティとパフォーマンスを考慮する必要があります。アプリケーションでリクエスト数が増加するたびに、アプリケーションはすぐに拡張を開始し、リソースを効率的に利用する必要があります。

GraalVM で Spring Boot Ahead of Time (AOT) コンパイルを使用し、Java 仮想スレッド (JDK 21 以降で利用可能) とともにコンテナ内で実行可能ファイルを実行することを検討しています。

  • AOT コンパイルは、実行時の適応性が低下する代わりに、高速な起動時間と予測可能なパフォーマンスが重要であるシナリオに有利です。
  • コンテナはホスト OS カーネルを共有するため、軽量であり、仮想マシン (VM) に比べて使用するリソースが少なくなります。コンテナは VM よりもはるかに高速に起動および停止できるため、より迅速なスケーリングとデプロイが可能になります。
  • 仮想スレッドは、多数の同時タスクを処理するアプリケーションのパフォーマンスを向上させることができます。これは、Web サーバー、データベース、その他の I/O バウンド システムなどのアプリケーションにとって特に有益です。仮想スレッドは、従来のスレッドよりも使用するリソースが少なくなります。これらは、メモリ使用量と CPU オーバーヘッドを最小限に抑える方法でランタイムによって管理されます。

このアーキテクチャ設計の決定では利点が得られますが、次の実装上の課題と設計上の考慮事項も考慮する必要があります。

  • 仮想スレッド: 大量のメモリ計算を必要とするシナリオなど、ビジネス ロジックが CPU を集中的に使用する場合は、仮想スレッドの使用を避ける必要があります。
  • Ahead of Time (AOT) コンパイル: AOT コンパイラーは、リフレクション、プロキシ コーディング、またはシリアル化を適切に処理できない可能性があります。さらに、GraalVM は比較的新しいテクノロジーであるため、Spring Boot アプリケーションからネイティブ イメージを作成する際に課題が生じ、ビルド時間の増加につながります。
  • コンテナ: コンテナには多くの利点がありますが、セキュリティ、ネットワーク、パフォーマンス、CI/CD などの領域に関連する課題もいくつかあります。例のいくつかは次のとおりです。
    • コンテナには、基本イメージまたは依存関係からの脆弱性が含まれる可能性があります。
    • コンテナを既存の CI/CD パイプラインに統合することは困難な場合があり、ビルド、テスト、デプロイメントのプロセスに変更を加える必要があります。
    • Kubernetes などのコンテナ オーケストレーション プラットフォームの管理は複雑になる場合があり、専門知識が必要です。
    • リソースを過剰にプロビジョニングしたり、過小プロビジョニングしたりすることなく、コンテナーを効率的にスケールアップおよびスケールダウンして、さまざまな負荷を処理します。

Spring Boot アプリケーション
このユースケースをテストするために、「/hello」で REST エンドポイントを公開する Spring Boot アプリケーションを構築しています。次の構成、ライブラリ、ツールを使用しています:

  • Spring Boot 3.2.8 (REST あり)
  • 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” の構成。このイメージは Alpine Linux ボックスで実行するため、「libc musl」互換ライブラリを使用してネイティブ イメージをビルドするように GraalVM を構成しています。 Musl は、他の標準ライブラリと比較してサイズが小さく、使用するメモリが少なくなるように設計されているため、リソースに制約のある環境に適しています。

バイナリをビルドして Docker イメージを作成する

コンテナ内でネイティブ イメージが実行される、特定の OS ホストと CPU アーキテクチャ用のネイティブ イメージを構築する必要があります。

コンテナ内でアプリケーションを実行するために、サイズの小ささ、シンプルさ、セキュリティの点で Alpine Linux を使用しています。これを実現するには、アプリケーションの構築に適切な GraalVM 構成を使用する必要があります。 Alpine のシステム要件は、オペレーティング システムと CPU アーキテクチャです。

  • 「アーキテクチャ」: "amd64"
  • 「OS」: "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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
JVMは、Javaの「Write and、Run Anywhere」(Wora)機能にどのように貢献しますか?JVMは、Javaの「Write and、Run Anywhere」(Wora)機能にどのように貢献しますか?May 02, 2025 am 12:25 AM

JVMは、バイトコード解釈、プラットフォームに依存しないAPI、動的クラスの負荷を介してJavaのWORA機能を実装します。 2。標準API抽象オペレーティングシステムの違い。 3.クラスは、実行時に動的にロードされ、一貫性を確保します。

Javaの新しいバージョンは、プラットフォーム固有の問題にどのように対処しますか?Javaの新しいバージョンは、プラットフォーム固有の問題にどのように対処しますか?May 02, 2025 am 12:18 AM

Javaの最新バージョンは、JVMの最適化、標準的なライブラリの改善、サードパーティライブラリサポートを通じて、プラットフォーム固有の問題を効果的に解決します。 1)Java11のZGCなどのJVM最適化により、ガベージコレクションのパフォーマンスが向上します。 2)Java9のモジュールシステムなどの標準的なライブラリの改善は、プラットフォーム関連の問題を削減します。 3)サードパーティライブラリは、OpenCVなどのプラットフォーム最適化バージョンを提供します。

JVMによって実行されたバイトコード検証のプロセスを説明します。JVMによって実行されたバイトコード検証のプロセスを説明します。May 02, 2025 am 12:18 AM

JVMのバイトコード検証プロセスには、4つの重要な手順が含まれます。1)クラスファイル形式が仕様に準拠しているかどうかを確認し、2)バイトコード命令の有効性と正確性を確認し、3)データフロー分析を実行してタイプの安全性を確保し、検証の完全性とパフォーマンスのバランスをとる。これらの手順を通じて、JVMは、安全で正しいバイトコードのみが実行されることを保証し、それによりプログラムの完全性とセキュリティを保護します。

プラットフォームの独立性は、Javaアプリケーションの展開をどのように簡素化しますか?プラットフォームの独立性は、Javaアプリケーションの展開をどのように簡素化しますか?May 02, 2025 am 12:15 AM

java'splatformendencealLowsApplicationStorunOperatingSystemwithajvm.1)singlecodebase:writeandcompileonceforallplatforms.2)easyUpdates:updatebytecodeforsimultaneousdeployment.3)テストの実験効果:scalbortffortfforduniverbehaviol.4)

Javaのプラットフォームの独立性は、時間とともにどのように進化しましたか?Javaのプラットフォームの独立性は、時間とともにどのように進化しましたか?May 02, 2025 am 12:12 AM

Javaのプラットフォームの独立性は、JVM、JITコンピレーション、標準化、ジェネリック、ラムダ式、Projectpanamaなどのテクノロジーを通じて継続的に強化されています。 1990年代以来、Javaは基本的なJVMから高性能モダンJVMに進化し、さまざまなプラットフォームでのコードの一貫性と効率を確保しています。

Javaアプリケーションでプラットフォーム固有の問題を緩和するためのいくつかの戦略は何ですか?Javaアプリケーションでプラットフォーム固有の問題を緩和するためのいくつかの戦略は何ですか?May 01, 2025 am 12:20 AM

Javaはプラットフォーム固有の問題をどのように軽減しますか? Javaは、JVMおよび標準ライブラリを通じてプラットフォームに依存します。 1)bytecodeとjvmを使用して、オペレーティングシステムの違いを抽象化します。 2)標準のライブラリは、パスクラス処理ファイルパス、CHARSETクラス処理文字エンコードなど、クロスプラットフォームAPIを提供します。 3)最適化とデバッグのために、実際のプロジェクトで構成ファイルとマルチプラットフォームテストを使用します。

Javaのプラットフォームの独立性とマイクロサービスアーキテクチャの関係は何ですか?Javaのプラットフォームの独立性とマイクロサービスアーキテクチャの関係は何ですか?May 01, 2025 am 12:16 AM

java'splatformentencentenhancesmicroservicesecturectureby byofferingdeploymentflexability、一貫性、スケーラビリティ、およびポート可能性。1)展開の展開の展開は、AllosmicRoserviThajvm.2)deploymentflexibility lowsmicroserviceSjvm.2)一貫性のあるAcrossServicessimplisimpligiessdevelisementand

GraalvmはJavaのプラットフォーム独立目標とどのように関係していますか?GraalvmはJavaのプラットフォーム独立目標とどのように関係していますか?May 01, 2025 am 12:14 AM

Graalvmは、Javaのプラットフォームの独立性を3つの方法で強化します。1。言語間の相互運用性、Javaが他の言語とシームレスに相互運用できるようにします。 2。独立したランタイム環境、graalvmnativeimageを介してJavaプログラムをローカル実行可能ファイルにコンパイルします。 3.パフォーマンスの最適化、Graalコンパイラは、Javaプログラムのパフォーマンスと一貫性を改善するための効率的なマシンコードを生成します。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!