SpringBootのWarパッケージをDockerコンテナ化してみる

<h1>目的</h1>
<p>Springbootアプリケーションをコンテナ化したことがなく、SpringbootのDockerコンテナ化の記事は見るが、Warパッケージのコンテナ化の記事は見た記憶がないのでWarでも問題なくコンテナ化できるか確認と練習のため。自分用メモ<p>

<h2>プロジェクトの用意</h2>
<span>コンテナ化の確認のためだけなので依存関係は最小限（画像はGradleになっているがMaven選択）</span>

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/673518/edf0280f-b3a0-eb98-3fef-af7bbed5dc1c.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/673518/b0f3b083-d6f8-071c-e448-2b8bdf6128ba.png)


```pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ryo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

```
<br>
<h2>コード</h2>
<p>Hello文字列を返却するだけのRestControllerを定義</p>

~~~Controller.java

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {
    @GetMapping("/hello")
    public String ts(){
        return "Hello";
    }
}
~~~

<h2>Dockerfileの作成</h2>
<p>公式のJDKのイメージにはJREがないとのことだったので、とりあえずは参考文献の勧め通りのイメージを使用、Dockerfileはプロジェクトの直下に配置</p>

```Dockerfile
FROM eclipse-temurin:17-jdk-jammy as builder
WORKDIR /opt/app
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY ./src ./src
RUN ./mvnw clean install
 
FROM eclipse-temurin:17-jre-jammy
WORKDIR /opt/app
EXPOSE 8080
COPY --from=builder /opt/app/target/*.war /opt/app/*.war
ENTRYPOINT ["java", "-jar", "/opt/app/*.war"]

```

<h2>Docker compose</h2>
<p>DockerComposeの設定ファイルを記載、こちらもプロジェクト直下に配置。上記で作成したDockerfileを直接ビルドするように設定</p>

```docker-compose.yaml
version: '3'
services:
  # Javaの設定情報
  java:
    # コンテナ名
    container_name: spring
    build: 
      context: .
      dockerfile: Dockerfile
    ports:
     - "8080:8080"
```

<h2>コンテナの起動、確認</h2>
<p>コンテナを起動、localhostにアクセスしたところ文字列の表示が確認できた。とりあえずはWarでもJarの例とそんなに変わらずに起動できそう。</p>

```cmd
PS C:\expenses-app\demo> docker compose up
[+] Building 1.5s (17/17) FINISHED                                                                                              docker:default
 => [java internal] load build definition from Dockerfile                                                                                 0.0s
 => => transferring dockerfile: 394B                                                                                                      0.0s
 => [java internal] load .dockerignore                                                                                                    0.0s
 => => transferring context: 2B                                                                                                           0.0s
 => [java internal] load metadata for docker.io/library/eclipse-temurin:17-jre-jammy                                                      1.3s
 => [java internal] load metadata for docker.io/library/eclipse-temurin:17-jdk-jammy                                                      1.4s
 => [java auth] library/eclipse-temurin:pull token for registry-1.docker.io                                                               0.0s
 => [java builder 1/7] FROM docker.io/library/eclipse-temurin:17-jdk-jammy@sha256:d87a5e63a3d0cc562a8c9207328311d72f9aaf8948b5ee082acf4c  0.0s
 => [java stage-1 1/3] FROM docker.io/library/eclipse-temurin:17-jre-jammy@sha256:aa1f60eb5c86df76fa2189f36eb062592748a733a9eaf577dcb20f  0.0s
 => [java internal] load build context                                                                                                    0.0s
 => => transferring context: 1.10kB                                                                                                       0.0s
 => CACHED [java stage-1 2/3] WORKDIR /opt/app                                                                                            0.0s
 => CACHED [java builder 2/7] WORKDIR /opt/app                                                                                            0.0s
 => CACHED [java builder 3/7] COPY .mvn/ .mvn                                                                                             0.0s
 => CACHED [java builder 4/7] COPY mvnw pom.xml ./                                                                                        0.0s
 => CACHED [java builder 5/7] RUN ./mvnw dependency:go-offline                                                                            0.0s
 => CACHED [java builder 6/7] COPY ./src ./src                                                                                            0.0s
 => CACHED [java builder 7/7] RUN ./mvnw clean install                                                                                    0.0s
 => CACHED [java stage-1 3/3] COPY --from=builder /opt/app/target/*.war /opt/app/*.war                                                    0.0s
 => [java] exporting to image                                                                                                             0.0s
 => => exporting layers                                                                                                                   0.0s
 => => writing image sha256:0733b6b9cdf4f7b5e01b9f7104a225a09aff43e49993b4c3ac50616ebc2ca964                                              0.0s
 => => naming to docker.io/library/demo-java                                                                                              0.0s
[+] Running 1/1
 ✔ Container spring  Created                                                                                                              0.1s
Attaching to spring
spring  |
spring  |   .   ____          _            __ _ _
spring  |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
spring  | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring  |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
spring  |   '  |____| .__|_| |_|_| |_\__, | / / / /
spring  |  =========|_|==============|___/=/_/_/_/
spring  |  :: Spring Boot ::                (v3.2.1)
spring  |
spring  | 2024-01-16T16:20:56.724Z  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication using Java 17.0.9 with PID 1 (/opt/app/*.war started by root in /opt/app)
spring  | 2024-01-16T16:20:56.733Z  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to 1 default profile: "default"
spring  | 2024-01-16T16:20:57.412Z  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
spring  | 2024-01-16T16:20:57.419Z  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
spring  | 2024-01-16T16:20:57.420Z  INFO 1 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.17]
spring  | 2024-01-16T16:20:57.458Z  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
spring  | 2024-01-16T16:20:57.459Z  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 668 ms
spring  | 2024-01-16T16:20:57.676Z  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path ''
spring  | 2024-01-16T16:20:57.685Z  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 1.254 seconds (process running for 1.549)
spring  | 2024-01-16T16:21:05.082Z  INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
spring  | 2024-01-16T16:21:05.082Z  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
spring  | 2024-01-16T16:21:05.083Z  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms

```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/673518/39a727c1-3283-99a2-229e-4a5cbd8194e7.png)


<h2>参考文献</h2>
https://www.docker.com/ja-jp/blog/9-tips-for-containerizing-your-spring-boot-code/