Java 原生应用容器化规范

注意:适用于 ACP v3.14.3、v3.16.2、v3.18 及以上版本。

仅当 Java 应用使用 JAVA_TOOL_OPTIONS 环境变量时,才必须遵循以下容器化规范,以确保应用自身对 JAVA_TOOL_OPTIONS 环境变量的配置能够生效。具体而言,在 Container Platform 中部署时,应用的 Deployment 应显式声明 JAVA_TOOL_OPTIONS 环境变量。示例如下:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: your-java-app
spec:
  template:
    spec:
      containers:
        - env: # Configuration examples
            - name: JAVA_TOOL_OPTIONS
              value: "-Xmx1024m -Xms512m"
          name: your-java-app

原因:当将 Java 应用(Deployment)以服务(OpenTelemetry governance)的形式添加到平台时,系统会通过向 pod 的 JAVA_TOOL_OPTIONS 环境变量追加 -javaagent 参数来自动注入 Java Agent,例如 -javaagent:/otel-auto-instrumentation-java/javaagent.jar。如果以其他方式配置 JAVA_TOOL_OPTIONS,则可能会覆盖该设置。

Java 原生应用容器化规范(旧)

注意:适用于除上述新规范之外的其他 ACP 版本。

为确保平台的治理能力能够有效应用于您的 Java 应用,请在开发和构建过程中遵循以下 Java 原生应用容器化规范:

基础镜像选择

建议使用 JDK 8u212 或更高版本作为基础镜像。

Dockerfile 模板

请参考本文档中提供的 Dockerfile 模板和说明,并据此修改 Java 应用项目中使用的 Dockerfile 文件。

Dockerfile 模板如下:

FROM eclipse-temurin:8-alpine

VOLUME /tmp

# Set the container's timezone and add the admin account, also create its home directory.
# Note: The instruction to set the timezone may vary depending on the OS of the base image.
# Note: This step requires accessing the internet to download dependencies. If you are in an isolated internal network, consider using a public base image to complete this step.
RUN apk update \
    && apk add --no-cache tzdata \
    && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && echo "Asia/Shanghai" > /etc/timezone \
    && adduser -D admin

# The WORKDIR instruction makes it easier to use relative paths in subsequent instructions to simplify the script.
WORKDIR /home/admin/

# For security reasons, use a non-root account to avoid running commands like apt-get.
USER admin

# The COPY --chown option eliminates the need to run chown again.
# Note: Ensure that start.sh has executable permissions.
COPY --chown=admin:admin start.sh \
     target/app.jar \
     /home/admin/

# Start the container by executing the script.
ENTRYPOINT ["./start.sh"]

Dockerfile 模板中引用的 start.sh 脚本内容如下。请将脚本文件保存在与 Dockerfile 相同的目录中。

#!/bin/sh

# -e Exit immediately if a command exits with a non-zero status.
# -x Display commands and their arguments as they are executed.
set -ex

# Use the value of the JAVA_OPTS environment variable as the startup parameter for the JAVA service, automatically replacing it with the value of the JAVA_OPTS environment variable in the current environment at runtime.
# Use exec so that the Java program can receive the SIGTERM signal.
exec /usr/bin/java ${JAVA_OPTS} \
     -Djava.security.egd=file:/dev/./urandom \
     -jar /home/admin/app.jar ${RUN_ARGS} "$@"