將 Java 應用程式容器化

先決條件

  • 您已安裝最新版本的 Docker Desktop。 Docker 會定期新增新功能,本指南的某些部分可能僅適用於最新版本的 Docker Desktop。
  • 您已安裝 Git 用戶端。本節中的範例使用基於命令列的 Git 用戶端,但您可以使用任何用戶端。

概觀

本節將引導您完成 Java 應用程式的容器化和執行。

取得範例應用程式

將您將在本機開發機器上使用的範例應用程式複製到您的電腦。在終端機中執行以下命令以複製儲存庫。

$ git clone https://github.com/spring-projects/spring-petclinic.git

範例應用程式是一個使用 Maven 建置的 Spring Boot 應用程式。如需詳細資訊,請參閱儲存庫中的 `readme.md`。

初始化 Docker 資產

現在您有了一個應用程式,您可以建立必要的 Docker 資產來將您的應用程式容器化。您可以使用 Docker Desktop 內建的 Docker Init 功能來簡化流程,或者您可以手動建立資產。


在 `spring-petclinic` 目錄中,執行 `docker init` 命令。`docker init` 提供一些預設配置,但您需要回答一些關於您應用程式的問題。請參考以下範例來回答 `docker init` 的提示,並對您的提示使用相同的答案。

範例應用程式已包含 Docker 資產。系統將提示您覆蓋現有的 Docker 資產。要繼續本指南,請選擇 `y` 覆蓋它們。

$ docker init
Welcome to the Docker Init CLI!

This utility will walk you through creating the following files with sensible defaults for your project:
  - .dockerignore
  - Dockerfile
  - compose.yaml
  - README.Docker.md

Let's get started!

WARNING: The following Docker files already exist in this directory:
  - docker-compose.yml
? Do you want to overwrite them? Yes
? What application platform does your project use? Java
? What's the relative directory (with a leading .) for your app? ./src
? What version of Java do you want to use? 21
? What port does your server listen on? 8080

在上一個範例中,請注意 `WARNING`。`docker-compose.yaml` 已存在,因此 `docker init` 會覆蓋該檔案,而不是建立新的 `compose.yaml` 檔案。這可以防止目錄中有多個 Compose 檔案。這兩個名稱都受支援,但 Compose 偏好使用標準的 `compose.yaml`。

如果您沒有安裝 Docker Desktop 或偏好手動建立資產,您可以在您的專案目錄中建立以下檔案。

建立一個名為 `Dockerfile` 的檔案,並使用以下內容。

Dockerfile
# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docker-docs.dev.org.tw/go/dockerfile-reference/

# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7

################################################################################

# Create a stage for resolving and downloading dependencies.
FROM eclipse-temurin:21-jdk-jammy as deps

WORKDIR /build

# Copy the mvnw wrapper with executable permissions.
COPY --chmod=0755 mvnw mvnw
COPY .mvn/ .mvn/

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.m2 so that subsequent builds don't have to
# re-download packages.
RUN --mount=type=bind,source=pom.xml,target=pom.xml \
    --mount=type=cache,target=/root/.m2 ./mvnw dependency:go-offline -DskipTests

################################################################################

# Create a stage for building the application based on the stage with downloaded dependencies.
# This Dockerfile is optimized for Java applications that output an uber jar, which includes
# all the dependencies needed to run your app inside a JVM. If your app doesn't output an uber
# jar and instead relies on an application server like Apache Tomcat, you'll need to update this
# stage with the correct filename of your package and update the base image of the "final" stage
# use the relevant app server, e.g., using tomcat (https://hub.docker.com/_/tomcat/) as a base image.
FROM deps as package

WORKDIR /build

COPY ./src src/
RUN --mount=type=bind,source=pom.xml,target=pom.xml \
    --mount=type=cache,target=/root/.m2 \
    ./mvnw package -DskipTests && \
    mv target/$(./mvnw help:evaluate -Dexpression=project.artifactId -q -DforceStdout)-$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout).jar target/app.jar

################################################################################

# Create a stage for extracting the application into separate layers.
# Take advantage of Spring Boot's layer tools and Docker's caching by extracting
# the packaged application into separate layers that can be copied into the final stage.
# See Spring's docs for reference:
# https://spring-docs.dev.org.tw/spring-boot/docs/current/reference/html/container-images.html
FROM package as extract

WORKDIR /build

RUN java -Djarmode=layertools -jar target/app.jar extract --destination target/extracted

################################################################################

# Create a new stage for running the application that contains the minimal
# runtime dependencies for the application. This often uses a different base
# image from the install or build stage where the necessary files are copied
# from the install stage.
#
# The example below uses eclipse-turmin's JRE image as the foundation for running the app.
# By specifying the "17-jre-jammy" tag, it will also use whatever happens to be the
# most recent version of that tag when you build your Dockerfile.
# If reproducibility is important, consider using a specific digest SHA, like
# eclipse-temurin@sha256:99cede493dfd88720b610eb8077c8688d3cca50003d76d1d539b0efc8cca72b4.
FROM eclipse-temurin:21-jre-jammy AS final

# Create a non-privileged user that the app will run under.
# See https://docker-docs.dev.org.tw/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    appuser
USER appuser

# Copy the executable from the "package" stage.
COPY --from=extract build/target/extracted/dependencies/ ./
COPY --from=extract build/target/extracted/spring-boot-loader/ ./
COPY --from=extract build/target/extracted/snapshot-dependencies/ ./
COPY --from=extract build/target/extracted/application/ ./

EXPOSE 8080

ENTRYPOINT [ "java", "org.springframework.boot.loader.launch.JarLauncher" ]

範例中已包含一個 Compose 檔案。覆蓋此檔案以繼續進行指南。使用以下內容更新 `docker-compose.yaml`。

docker-compose.yaml
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docker-docs.dev.org.tw/go/compose-spec-reference/

# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
  server:
    build:
      context: .
    ports:
      - 8080:8080
# The commented out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker-compose up`.
#     depends_on:
#       db:
#         condition: service_healthy
#   db:
#     image: postgres
#     restart: always
#     user: postgres
#     secrets:
#       - db-password
#     volumes:
#       - db-data:/var/lib/postgresql/data
#     environment:
#       - POSTGRES_DB=example
#       - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
#     expose:
#       - 5432
#     healthcheck:
#       test: [ "CMD", "pg_isready" ]
#       interval: 10s
#       timeout: 5s
#       retries: 5
# volumes:
#   db-data:
# secrets:
#   db-password:
#     file: db/password.txt

建立一個名為 `.dockerignore` 的檔案,並使用以下內容。

.dockerignore
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docker-docs.dev.org.tw/go/build-context-dockerignore/

**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.next
**/.cache
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/charts
**/docker-compose*
**/compose.y*ml
**/target
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
**/vendor
LICENSE
README.md

您現在應該在 `spring-petclinic` 目錄中有以下三個檔案。

執行應用程式

在 `spring-petclinic` 目錄中,於終端機中執行以下命令。

$ docker compose up --build

第一次建置和執行應用程式時,Docker 會下載依賴項並建置應用程式。根據您的網路連線,這可能需要幾分鐘時間。

開啟瀏覽器並在 http://localhost:8080檢視應用程式。您應該會看到一個寵物診所的簡單應用程式。

在終端機中,按 `ctrl`+`c` 停止應用程式。

在背景執行應用程式

您可以透過新增 `-d` 選項,讓應用程式與終端機分離執行。在 `spring-petclinic` 目錄中,於終端機中執行以下命令。

$ docker compose up --build -d

開啟瀏覽器並在 http://localhost:8080檢視應用程式。您應該會看到一個寵物診所的簡單應用程式。

在終端機中,執行以下命令以停止應用程式。

$ docker compose down

如需 Compose 命令的詳細資訊,請參閱 Compose CLI 參考

摘要

在本節中,您學習了如何使用 Docker 將 Java 應用程式容器化和執行。

相關資訊

後續步驟

在下一節中,您將學習如何使用 Docker 容器開發您的應用程式。