【初心者向け】Spring BootによるWebアプリ開発ハンズオン ~Step5:Linuxサーバへのデプロイ~

1. はじめに

本シリーズではSpring Boot3を用いてクイズアプリの開発する方法をご紹介しています。ひととおり実践して基礎を理解してもらえれば、自分が作りたいWebアプリを開発することができると思いますので、ぜひ挑戦してみてください。Step4まででご自身のIDE上ではアプリが起動するようになったと思いますので、Step5ではLinuxサーバ(CentOS8)の環境で動作させる方法をご紹介したいと思います。
【Java】Spring Boot 3によるWebアプリ開発入門 ~Step1:環境構築~
【Java】Spring Boot 3によるWebアプリ開発入門~Step2:データベース構築~
【Java】Spring Boot 3によるWebアプリ開発入門 ~Step3:クイズアプリ実装~
【Java】Spring Boot 3によるWebアプリ開発入門 ~Step4:Spring Securityによるログイン機能~

2. 前提環境

VirtualBoxに作成した仮想マシン(CentOS 8.5)の上でアプリを動作させていきます。仮想マシンの構築については下記でまとめてますのでご参照ください。
【VirtualBox】ゲストOS(CentOS)のネットワーク設定 ~SSH接続/インターネット接続~

3. OpenJDKのインストール

Spring bootアプリを実行するためにOpenJDKをインストールします。ここではOpenJDK21をインストールしていきます。
まず、OpenJDKインストール先のディレクトリを作成して、作成したディレクトリに移動します。

[root@masternode ~]# mkdir /opt/java
[root@masternode ~]# ls -ld /opt/java/
drwxr-xr-x 2 root root 6 Jan 31 07:24 /opt/java/
[root@masternode ~]#
[root@masternode ~]# cd /opt/java/
[root@masternode java]#

続いてOpenJDKインストール用のファイルをダウンロードします。

[root@masternode java]# wget https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.tar.gz
--2025-01-31 07:26:37--  https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.tar.gz
Resolving download.oracle.com (download.oracle.com)... 202.226.44.99
Connecting to download.oracle.com (download.oracle.com)|202.226.44.99|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 197405999 (188M) [application/x-gzip]
Saving to: ‘jdk-21_linux-x64_bin.tar.gz’

jdk-21_linux-x64_bin.tar.gz           100%[=======================================================================>] 188.26M  7.13MB/s    in 97s

2025-01-31 07:28:14 (1.94 MB/s) - ‘jdk-21_linux-x64_bin.tar.gz’ saved [197405999/197405999]

[root@masternode java]# ls -l jdk-21_linux-x64_bin.tar.gz
-rw-r--r-- 1 root root 197405999 Dec  3 20:08 jdk-21_linux-x64_bin.tar.gz
[root@masternode java]#

ダウンロードしたtar.gzファイルを解凍します。

[root@masternode java]# tar zxvf jdk-21_linux-x64_bin.tar.gz
jdk-21.0.6/LICENSE
jdk-21.0.6/README
jdk-21.0.6/bin/jar

~~Omission~~

jdk-21.0.6/man/man1/rmiregistry.1
jdk-21.0.6/man/man1/serialver.1
jdk-21.0.6/release
[root@masternode java]#

jdk-21.0.6ディレクトリが作成されたら、tar.gzファイルは削除してしまいましょう。

[root@masternode java]# ll
total 192780
drwxr-xr-x 9 root root       136 Jan 31 07:43 jdk-21.0.6
-rw-r--r-- 1 root root 197405999 Dec  3 20:08 jdk-21_linux-x64_bin.tar.gz
[root@masternode java]#
[root@masternode java]# rm -f jdk-21_linux-x64_bin.tar.gz
[root@masternode java]#
[root@masternode java]# ll
total 0
drwxr-xr-x 9 root root 136 Jan 31 07:43 jdk-21.0.6
[root@masternode java]#

環境変数を設定して読み込んでください。

[root@masternode java]# vi /etc/profile
[root@masternode java]# cat /etc/profile
# /etc/profile

~~Omission~~

export JAVA_HOME=/opt/java/jdk-21.0.6
export PATH="$JAVA_HOME/bin:/opt/maven/default/bin:$PATH"
[root@masternode java]#
[root@masternode java]# source /etc/profile
[root@masternode java]#

下記コマンドを実行してください。javaのバージョンが表示されれば成功です。

[root@masternode java]# java --version
java 21.0.6 2025-01-21 LTS
Java(TM) SE Runtime Environment (build 21.0.6+8-LTS-188)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.6+8-LTS-188, mixed mode, sharing)
[root@masternode java]#

4. Postgresのインストール

データベースについては環境ごとに作成する必要がありますので、Postgres15を仮想サーバにインストールしていきましょう。まず、リポジトリをインストールします。

[root@masternode ~]# dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
Last metadata expiration check: 0:14:23 ago on Fri 17 Jan 2025 06:20:46 AM JST.
pgdg-redhat-repo-latest.noarch.rpm                                                             7.8 kB/s |  15 kB     00:01
Dependencies resolved.
===============================================================================================================================
 Package                           Architecture            Version                         Repository                     Size
===============================================================================================================================
Installing:
 pgdg-redhat-repo                  noarch                  42.0-45PGDG                     @commandline                   15 k

Transaction Summary
===============================================================================================================================
Install  1 Package

Total size: 15 k
Installed size: 17 k
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                       1/1
  Installing       : pgdg-redhat-repo-42.0-45PGDG.noarch                                                                   1/1
  Verifying        : pgdg-redhat-repo-42.0-45PGDG.noarch                                                                   1/1

Installed:
  pgdg-redhat-repo-42.0-45PGDG.noarch

Complete!
[root@masternode ~]#

続いて、postgresql15-serverをインストールします。

[root@masternode ~]# dnf install -y postgresql15-server
Last metadata expiration check: 0:05:08 ago on Fri 17 Jan 2025 06:30:22 AM JST.
Dependencies resolved.
===============================================================================================================================
 Package                              Architecture            Version                            Repository               Size
===============================================================================================================================
Installing:
 postgresql15-server                  x86_64                  15.10-1PGDG.rhel8                  pgdg15                  6.1 M
Installing dependencies:
 postgresql15                         x86_64                  15.10-1PGDG.rhel8                  pgdg15                  1.6 M
 postgresql15-libs                    x86_64                  15.10-1PGDG.rhel8                  pgdg15                  295 k

Transaction Summary
===============================================================================================================================
Install  3 Packages

Total download size: 8.0 M
Installed size: 34 M
Downloading Packages:
(1/3): postgresql15-libs-15.10-1PGDG.rhel8.x86_64.rpm                                           91 kB/s | 295 kB     00:03
(2/3): postgresql15-15.10-1PGDG.rhel8.x86_64.rpm                                               430 kB/s | 1.6 MB     00:03
(3/3): postgresql15-server-15.10-1PGDG.rhel8.x86_64.rpm                                        1.0 MB/s | 6.1 MB     00:05
-------------------------------------------------------------------------------------------------------------------------------
Total                                                                                          1.4 MB/s | 8.0 MB     00:05
PostgreSQL 15 for RHEL / Rocky / AlmaLinux 8 - x86_64                                          2.1 MB/s | 2.4 kB     00:00
Importing GPG key 0x08B40D20:
 Userid     : "PostgreSQL RPM Repository <pgsql-pkg-yum@lists.postgresql.org>"
 Fingerprint: D4BF 08AE 67A0 B4C7 A1DB CCD2 40BC A2B4 08B4 0D20
 From       : /etc/pki/rpm-gpg/PGDG-RPM-GPG-KEY-RHEL
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                       1/1
  Installing       : postgresql15-libs-15.10-1PGDG.rhel8.x86_64                                                            1/3
  Running scriptlet: postgresql15-libs-15.10-1PGDG.rhel8.x86_64                                                            1/3

~~Omission~~

  Verifying        : postgresql15-15.10-1PGDG.rhel8.x86_64                                                                 1/3
  Verifying        : postgresql15-libs-15.10-1PGDG.rhel8.x86_64                                                            2/3
  Verifying        : postgresql15-server-15.10-1PGDG.rhel8.x86_64                                                          3/3

Installed:
  postgresql15-15.10-1PGDG.rhel8.x86_64                           postgresql15-libs-15.10-1PGDG.rhel8.x86_64
  postgresql15-server-15.10-1PGDG.rhel8.x86_64

Complete!
[root@masternode ~]# 

Initdbコマンドでデータベースを初期化します。OKと出れば成功です。


[root@masternode ~]# /usr/pgsql-15/bin/postgresql-15-setup initdb
Initializing database ... OK

[root@masternode ~]# 

Postgresを起動します。ステータスがactivie(running)になっていることを確認して下さい。

[root@masternode ~]# systemctl start postgresql-15
[root@masternode ~]# systemctl status postgresql-15
● postgresql-15.service - PostgreSQL 15 database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql-15.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2025-01-17 06:36:07 JST; 3s ago
     Docs: https://www.postgresql.org/docs/15/static/
  Process: 33356 ExecStartPre=/usr/pgsql-15/bin/postgresql-15-check-db-dir ${PGDATA} (code=exited, status=0/SUCCESS)
 Main PID: 33363 (postmaster)
    Tasks: 7 (limit: 23554)
   Memory: 17.5M
   CGroup: /system.slice/postgresql-15.service
           ├─33363 /usr/pgsql-15/bin/postmaster -D /var/lib/pgsql/15/data/
           ├─33365 postgres: logger
           ├─33366 postgres: checkpointer
           ├─33367 postgres: background writer
           ├─33369 postgres: walwriter
           ├─33370 postgres: autovacuum launcher
           └─33371 postgres: logical replication launcher

Jan 17 06:36:07 masternode systemd[1]: Starting PostgreSQL 15 database server...
Jan 17 06:36:07 masternode postmaster[33363]: 2025-01-17 06:36:07.501 JST [33363] LOG:  redirecting log output to logging coll>
Jan 17 06:36:07 masternode postmaster[33363]: 2025-01-17 06:36:07.501 JST [33363] HINT:  Future log output will appear in dire>
Jan 17 06:36:07 masternode systemd[1]: Started PostgreSQL 15 database server.


PostgreSQL: Linux downloads (Red Hat family)

Postgresユーザにスイッチして、psqlコマンドでデータベースにアクセスしてみて下さい。

[root@masternode ~]# su - postgres
[postgres@masternode ~]$
[postgres@masternode ~]$ psql
psql: /usr/pgsql-15/lib/libpq.so.5: no version information available (required by psql)
psql: /usr/pgsql-15/lib/libpq.so.5: no version information available (required by psql)
psql (10.17, server 15.10)
WARNING: psql major version 10, server major version 15.
         Some psql features might not work.
Type "help" for help.

postgres=#

Postgresユーザに対してパスワードを付与します。

postgres=# ALTER USER postgres WITH PASSWORD 'password';
ALTER ROLE
postgres=#

パスワード認証を有効にします。下記の通りpg_hba.confを編集してpostgresサービスを再起動してください。

[root@appserver ~]# vi /var/lib/pgsql/data/pg_hba.conf
[root@appserver ~]#
[root@appserver ~]# diff /var/lib/pgsql/data/pg_hba.conf /var/lib/pgsql/data/pg_hba.conf_org
87c87
< host    all             all             127.0.0.1/32            md5
---
> host    all             all             127.0.0.1/32            ident
[root@appserver ~]#
[root@appserver ~]# systemctl restart postgresql
[root@appserver ~]#

続いて、サンプルアプリの動作に必要なquizデータベースを作成します。

postgres=# CREATE DATABASE quiz;
CREATE DATABASE
postgres=#

作成したquizデータベースに切り替えて、サンプルアプリに必要な各種テーブルを作成していきます。

postgres=# \c quiz
You are now connected to database "quiz" as user "postgres".
quiz=#
quiz=# create TABLE users_roles (
    user_id integer NOT NULL,
    role_id integer NOT NULL
);
CREATE TABLE
quiz=#
quiz=# create TABLE users (
    userid SERIAL NOT NULL,
    username varchar(255) NOT NULL UNIQUE,
    password varchar(255) NOT NULL,
    primary key (userid)
);
CREATE TABLE
quiz=#
quiz=# CREATE TABLE quiz (
    quizid SERIAL NOT NULL,
    userid integer NOT NULL,
    quiz varchar(255),
    category varchar(255),
    option1 varchar(255),
    option2 varchar(255),
    option3 varchar(255),
    option4 varchar(255),
    answer integer,
    explain varchar(1000),
    status varchar(255),
    PRIMARY KEY (quizid)
);
CREATE TABLE
quiz=#
quiz=# create TABLE roles (
    roleid SERIAL NOT NULL,
    rolename varchar(255) NOT NULL,
    primary key (roleid)
);
CREATE TABLE
quiz=#
quiz=#

サンプルデータをInsertしていきます。

quiz=# DO $$
quiz$# BEGIN
quiz$#     FOR i IN 1..1000 LOOP
quiz$#         INSERT INTO quiz (quizid,userid,quiz,category,option1,option2,option3,option4,answer,explain,status) VALUES(default,i,'Linuxのシステムに関する一般的なログファイル名は?','Linux','/var/log/logs','/var/log/messages','/var/log/maillog','/var/log/spooler','1','/var/log/messagesは、UnixおよびUnix系オペレーティングシステム(例えばLinux)で使用される標準的なログファイルの一つです。このファイルはシステムやアプリケーションからの重要なメッセージやイベントを記録するために使用されます。','未完了');
quiz$#         INSERT INTO quiz (quizid,userid,quiz,category,option1,option2,option3,option4,answer,explain,status)  VALUES(default,i,'ファイルの末尾から100行を表示させるコマンドは?','Linux','head -n 100','head -l 100','tail -n 100','tail -l 100','3','tailコ マンドは指定したファイルの末尾の内容を表示するための Linux コマンドです。オプション-nで表示する行数を指定します。デフォルトでは最 後の 10 行を表示します。','未完了');
quiz$#         INSERT INTO quiz (quizid,userid,quiz,category,option1,option2,option3,option4,answer,explain,status)  VALUES(default,i,'新規作成するファイルのパーミッションが全て644になるようにする方法は?','Linux','umask 644','umask 022','chmod 644','chmod 022','2','umaskに022を指定するとデフォルトの権限は644となります。一方でディレクトリは755になりますので注意してください。','未完了'); 
quiz$#     END LOOP;
quiz$# END;
quiz$# $$;
DO
quiz=#
quiz=# select * from quiz;
 quizid | answer | category |
       explain                                                                                                             |    op
tion1    |      option2      |     option3      |     option4      |                                 quiz
         | status | userid
--------+--------+----------+-----------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------+------
---------+-------------------+------------------+------------------+--------------------------------------------------------------
---------+--------+--------
      1 |      1 | Linux    | /var/log/messagesは、UnixおよびUnix系オペレーティングシステム(例えばLinux)で使用される標準的なログ
ファイルの一つです。このファイルはシステムやアプリケーションからの重要なメッセージやイベントを記録するために使用されます。 | /var/
log/logs | /var/log/messages | /var/log/maillog | /var/log/spooler | Linuxのシステムに関する一般的なログファイル名は?
         | 未完了 |      1
      2 |      3 | Linux    | tailコマンドは指定したファイルの末尾の内容を表示するための Linux コマンドです。オプション-nで表示す
行数を指定します。デフォルトでは最後の 10 行を表示します。                                                                | head -
n 100   | head -l 100       | tail -n 100      | tail -l 100      | ファイルの末尾から100行を表示させるコマンドは?
        | 未完了 |      1
      3 |      2 | Linux    | umaskに022を指定するとデフォルトの権限は644となります。一方でディレクトリは755になりますので注意して
ください。                                                                                                                 | umask
 644     | umask 022         | chmod 644        | chmod 022        | 新規作成するファイルのパーミッションが全て644になるようにする
方法は? | 未完了 |      1
      4 |      1 | Linux    | /var/log/messagesは、UnixおよびUnix系オペレーティングシステム(例えばLinux)で使用される標準的なログ
ファイルの一つです。このファイルはシステムやアプリケーションからの重要なメッセージやイベントを記録するために使用されます。 | /var/
log/logs | /var/log/messages | /var/log/maillog | /var/log/spooler | Linuxのシステムに関する一般的なログファイル名は?
         | 未完了 |      2
      5 |      3 | Linux    | tailコマンドは指定したファイルの末尾の内容を表示するための Linux コマンドです。オプション-nで表示す
行数を指定します。デフォルトでは最後の 10 行を表示します。                                                                | head -
n 100   | head -l 100       | tail -n 100      | tail -l 100      | ファイルの末尾から100行を表示させるコマンドは?
        | 未完了 |      2
      6 |      2 | Linux    | umaskに022を指定するとデフォルトの権限は644となります。一方でディレクトリは755になりますので注意して
ください。                                                                                                                 | umask
 644     | umask 022         | chmod 644        | chmod 022        | 新規作成するファイルのパーミッションが全て644になるようにする
方法は? | 未完了 |      2
quiz=# 

publicユーザを登録します。本ユーザを登録しておかないとアプリ起動にエラーになるので忘れずに実施ください。

quiz=# INSERT INTO USERS (userid,username,password) VALUES(1,'public','password');
INSERT 0 1
quiz=#
quiz=# select * from users;
 userid | password | username
--------+----------+----------
      1 | password | public
(1 row)

quiz=#

5. アプリケーションのデプロイ(パターン1:クローン)

GitHubにアップロードしてあるアプリケーションをLinuxサーバにクローンする方法を記載します。まずはGit関連コマンドを使えるようにするために必要なパッケージをインストールします。

[root@masternode ~]# dnf install -y git-all
Last metadata expiration check: 0:56:29 ago on Sun 05 Jan 2025 08:06:10 AM JST.
Dependencies resolved.
==================================================================================================
 Package                    Arch     Version                                    Repository   Size
==================================================================================================
Installing:
 git-all                    noarch   2.27.0-1.el8                               appstream    48 k
Installing dependencies:
 apr                        x86_64   1.6.3-12.el8                               appstream   129 k
 apr-util                   x86_64   1.6.1-6.el8                                appstream   105 k
 
~~Omission~~

  tk-1:8.6.8-1.el8.x86_64
  utf8proc-2.1.1-5.module_el8.3.0+703+ba2f61b7.x86_64

Complete!
[root@masternode ~]#
[root@masternode ~]# git --version
git version 2.27.0
[root@masternode ~]#

続いて、アプリケーションデプロイ用のディレクトリを作成します。作成したディレクトリ上でgit cloneコマンドを実行してアプリケションをクローニングします。

[root@masternode ~]# mkdir /app
[root@masternode ~]# cd /app/
[root@masternode app]# git clone https://github.com/eeengineering/quizapp-step4.git /app/quizapp/
Cloning into 'quizapp'...
remote: Enumerating objects: 154, done.
remote: Counting objects: 100% (154/154), done.
remote: Compressing objects: 100% (96/96), done.
remote: Total 154 (delta 32), reused 154 (delta 32), pack-reused 0 (from 0)
Receiving objects: 100% (154/154), 147.00 KiB | 7.74 MiB/s, done.
Resolving deltas: 100% (32/32), done.
[root@masternode app]#

下記の通りに必要なファイルが存在することを確認して下さい。

[root@masternode app]# cd quizapp
[root@masternode quizapp]#
[root@masternode quizapp]# ll
total 28
-rw-r--r-- 1 root root  1233 Jan 19 08:16 HELP.md
-rw-r--r-- 1 root root 10284 Jan 19 08:16 mvnw
-rw-r--r-- 1 root root  6734 Jan 19 08:16 mvnw.cmd
-rw-r--r-- 1 root root  2027 Jan 19 08:16 pom.xml
drwxr-xr-x 2 root root    68 Jan 19 08:16 sql-scripts
drwxr-xr-x 3 root root    35 Jan 19 08:16 src
drwxr-xr-x 5 root root    61 Jan 19 08:16 target
[root@masternode quizapp]#

mavenコマンドを実行するために下記の通りパーミッションを変更して下さい。

[root@masternode quizapp]# chmod 755 mvnw*
[root@masternode quizapp]#
[root@masternode quizapp]# ll
total 28
-rw-r--r-- 1 root root  1233 Jan 19 09:43 HELP.md
-rwxr-xr-x 1 root root 10284 Jan 19 09:43 mvnw
-rwxr-xr-x 1 root root  6734 Jan 19 09:43 mvnw.cmd
-rw-r--r-- 1 root root  2027 Jan 19 09:43 pom.xml
drwxr-xr-x 2 root root    68 Jan 19 09:43 sql-scripts
drwxr-xr-x 3 root root    35 Jan 19 09:43 src
drwxr-xr-x 5 root root    61 Jan 19 09:43 target
[root@masternode quizapp]#

権限が変更できたら、mvnwコマンドを実行してアプリケーションを起動して下さい。下記のようにStarted QuizApplicationのログが出力されていればアプリケション実行成功です。

[root@masternode quizapp]# ./mvnw spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< com.luv2code.springboot:cruddemo >------------------
[INFO] Building cruddemo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:3.3.6:run (default-cli) > test-compile @ cruddemo >>>
[INFO]
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ cruddemo ---
 
~~Omission~~


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.6)

2025-01-19T08:18:45.113+09:00  INFO 238206 --- [  restartedMain] eeengineer.quizapp.QuizApplication       : Starting QuizApplication using Java 21.0.5 with PID 238206 (/tmp/quizapp-step4/target/classes started by root in /tmp/quizapp-step4)
2025-01-19T08:18:45.118+09:00  INFO 238206 --- [  restartedMain] eeengineer.quizapp.QuizApplication       : No active profile set, falling back to 1 default profile: "default"

~~Omission~~

2025-01-19T08:18:54.119+09:00  INFO 238206 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-01-19T08:18:54.140+09:00  INFO 238206 --- [  restartedMain] eeengineer.quizapp.QuizApplication       : Started QuizApplication in 9.79 seconds (process running for 10.906)

ブラウザを起動し、ご自身の仮想マシンのIPアドレスを指定してアプリにアクセスできるか確認してください。
アクセスURL: http://{仮想マシンのIPアドレス}:8080/quiz/public

6. アプリケーションのデプロイ(パターン2:Jarファイルデプロイ)

もうひとつのやり方として、Jarファイルを作成してデプロイする方法をご説明します。JarファイルとはJava Archiveファイルの略となりまして、コンパイル済みのclassファイル等がまとまったファイルになっております。Jarファイルを用いることでファイルサイズを圧縮できたり、他の環境に配布しやすくなるといったメリットがあります。

今回は依存ライブラリ等を含めたJarファイル(Executable Jar)を作成します。Executable Jarを作成するためにMaven Shade Pluginを導入しましょう。pom.xmlのbuildタグの中に設定を追加します。

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <id>shade-jar-with-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>eeengineer.quizapp.QuizApplication</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
        </plugin>
    </plugins>
  </build>
</project>

※Executable Jarを作成するためのPluginの比較があったので、興味がある方は参照してみて下さい。maven-assembly-pluginだとうまく動作しなかったので、特にこだわりなければmaven-shade-pluginの導入を推奨します。
comparison:maven plugin jar,assembly,shade

続いて、自身のIDE上でビルドしてJarファイルを作成してください。STS(Spring Tool Suite)における作成手順を記載します。
Package Explorerタブで対象アプリを右クリック⇒「Run As」⇒「Maven install」を選択してください。

下記の通りBUILD SUCCESSのメッセージが出ていれば成功です。

[INFO] Scanning for projects...
[INFO] 
[INFO] -----------------< com.eeengineer.springboot:quizapp>------------------
[INFO] Building quizapp 1.0
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- resources:3.3.1:resources(default-resources)@ quizapp ---
[INFO] Copying 1 resource from src\main\resources to target\classes
[INFO] Copying 9 resources from src\main\resources to target\classes

~~Omission~~

[INFO] Replacing original artifact with shaded artifact.
[INFO] Replacing C:\Users\xxxx\Documents\GoogleDrive\application\spring-project\quizapp\target\quizapp-1.0.jar with C:\Users\xxxx\Documents\GoogleDrive\application\spring-project\quizapp\target\quizapp-1.0-shaded.jar
[INFO] 
[INFO] --- install:3.1.3:install (default-install) @ quizapp ---
[INFO] Installing C:\Users\xxxx\Documents\GoogleDrive\application\spring-project\quizapp\dependency-reduced-pom.xml to C:\Users\xxxx\.m2\repository\com\eeengineer\springboot\quizapp\1.0\quizapp-1.0.pom
[INFO] Installing C:\Users\xxxx\Documents\GoogleDrive\application\spring-project\quizapp\target\quizapp-1.0.jar to C:\Users\xxxx\.m2\repository\com\eeengineer\springboot\quizapp\1.0\quizapp-1.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  17.976 s
[INFO] Finished at: 2025-02-14T07:56:46+09:00
[INFO] ------------------------------------------------------------------------

Package Explorerにtargetディレクトリ、およびjarファイルが作成されていることを確認してください。

quizapp-1.0.jarをLinuxサーバに配置してください。

[root@masternode app]# ll /app/quizapp/
total 51292
-rw-r--r-- 1 root root 52519892 Feb  1 07:24 quizapp-1.0.jar
[root@masternode app]#

java -jar コマンドでjarフィアルを実行します。下記の通りStarted QuizApplicationの文言が表示されれば成功です。

[root@masternode quizapp]# java -jar quizapp-1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.7)

2025-02-01T07:32:01.310+09:00  INFO 147069 --- [  restartedMain] eeengineer.quizapp.QuizApplication       : Starting QuizApplication v1.0 using Java 21.0.6 with PID 147069 (/app/quizapp/quizapp-1.0.jar started by root in /app/quizapp)
2025-02-01T07:32:01.318+09:00  INFO 147069 --- [  restartedMain] eeengineer.quizapp.QuizApplication       : No active profile set, falling back to 1 default profile: "default"
2025-02-01T07:32:01.490+09:00  INFO 147069 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2025-02-01T07:32:01.491+09:00  INFO 147069 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'

~~Omission~~

2025-02-01T07:32:15.756+09:00  INFO 147069 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2025-02-01T07:32:17.362+09:00  INFO 147069 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2025-02-01T07:32:17.469+09:00  INFO 147069 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-02-01T07:32:17.504+09:00  INFO 147069 --- [  restartedMain] eeengineer.quizapp.QuizApplication       : Started QuizApplication in 17.552 seconds (process running for 19.149)

7. まとめ

Spring BootアプリをLinuxサーバにデプロイする方法については以上となります。また、Spring BootによるWebアプリ開発ハンズオンとしても以上で終了となります。ここまで実施いただいた皆さんお疲れさまでした。クラウドやコンテナ上でアプリを動作させるハンズオンについても記載しますので、そちらも試してみてもらえると嬉しいです。

8. 参考文献

コメント