容器化一个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

在前面的例子中,请注意WARNINGdocker-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://docs.docker.com/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://docs.spring.io/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://docs.docker.com/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
<button @click="window.navigator.clipboard.writeText(atob(code).replaceAll(/^[\$>]\s+/gm, '')); copying = true; setTimeout(() => copying = false, 2000);" class="absolute right-3 top-3 z-10 text-gray-light-300 dark:text-gray-dark-600" title="复制" x-data="{ code: 'IyBDb21tZW50cyBhcmUgcHJvdmlkZWQgdGhyb3VnaG91dCB0aGlzIGZpbGUgdG8gaGVscCB5b3UgZ2V0IHN0YXJ0ZWQuCiMgSWYgeW91IG5lZWQgbW9yZSBoZWxwLCB2aXNpdCB0aGUgRG9ja2VyIENvbXBvc2UgcmVmZXJlbmNlIGd1aWRlIGF0CiMgaHR0cHM6Ly9kb2NzLmRvY2tlci5jb20vZ28vY29tcG9zZS1zcGVjLXJlZmVyZW5jZS8KCiMgSGVyZSB0aGUgaW5zdHJ1Y3Rpb25zIGRlZmluZSB5b3VyIGFwcGxpY2F0aW9uIGFzIGEgc2VydmljZSBjYWxsZWQgInNlcnZlciIuCiMgVGhpcyBzZXJ2aWNlIGlzIGJ1aWx0IGZyb20gdGhlIERvY2tlcmZpbGUgaW4gdGhlIGN1cnJlbnQgZGlyZWN0b3J5LgojIFlvdSBjYW4gYWRkIG90aGVyIHNlcnZpY2VzIHlvdXIgYXBwbGljYXRpb24gbWF5IGRlcGVuZCBvbiBoZXJlLCBzdWNoIGFzIGEKIyBkYXRhYmFzZSBvciBhIGNhY2hlLiBGb3IgZXhhbXBsZXMsIHNlZSB0aGUgQXdlc29tZSBDb21wb3NlIHJlcG9zaXRvcnk6CiMgaHR0cHM6Ly9naXRodWIuY29tL2RvY2tlci9hd2Vzb21lLWNvbXBvc2UKc2VydmljZXM6CiAgc2VydmVyOgogICAgYnVpbGQ6CiAgICAgIGNvbnRleHQ6IC4KICAgIHBvcnRzOgogICAgICAtIDgwODA6ODA4MAojIFRoZSBjb21tZW50ZWQgb3V0IHNlY3Rpb24gYmVsb3cgaXMgYW4gZXhhbXBsZSBvZiBob3cgdG8gZGVmaW5lIGEgUG9zdGdyZVNRTAojIGRhdGFiYXNlIHRoYXQgeW91ciBhcHBsaWNhdGlvbiBjYW4gdXNlLiBgZGVwZW5kc19vbmAgdGVsbHMgRG9ja2VyIENvbXBvc2UgdG8KIyBzdGFydCB0aGUgZGF0YWJhc2UgYmVmb3JlIHlvdXIgYXBwbGljYXRpb24uIFRoZSBgZGItZGF0YWAgdm9sdW1lIHBlcnNpc3RzIHRoZQojIGRhdGFiYXNlIGRhdGEgYmV0d2VlbiBjb250YWluZXIgcmVzdGFydHMuIFRoZSBgZGItcGFzc3dvcmRgIHNlY3JldCBpcyB1c2VkCiMgdG8gc2V0IHRoZSBkYXRhYmFzZSBwYXNzd29yZC4gWW91IG11c3QgY3JlYXRlIGBkYi9wYXNzd29yZC50eHRgIGFuZCBhZGQKIyBhIHBhc3N3b3JkIG9mIHlvdXIgY2hvb3NpbmcgdG8gaXQgYmVmb3JlIHJ1bm5pbmcgYGRvY2tlci1jb21wb3NlIHVwYC4KIyAgICAgZGVwZW5kc19vbjoKIyAgICAgICBkYjoKIyAgICAgICAgIGNvbmRpdGlvbjogc2VydmljZV9oZWFsdGh5CiMgICBkYjoKIyAgICAg
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docs.docker.com/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://docs.docker.com/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容器开发您的应用程序。