gongxiangp2/Dockerfile

269 lines
17 KiB
Docker
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 基础镜像(使用 Alpine,手动处理 OpenSSL 兼容性)
# 固定 Node 24 LTS 的 Docker Hub 官方多架构清单。
# Docker Hub 官方多架构清单 digest。生产默认值必须是不可变引用;本地测试
# 如需改镜像源,仍可显式传入 BASE_IMAGE,但发布脚本不得覆盖此默认值。
ARG BASE_IMAGE=node:24.22.1-alpine@sha256:06d7adf3e0ef61a13f1d28682726366f97a15aa1888c934d3ecec86c33918b53
ARG ALPINE_MIRROR=https://mirrors.tuna.tsinghua.edu.cn/alpine
# Local/CI builds remain possible without Git metadata. Production deployment
# supplies the exact SHA and rejects this sentinel before any container starts.
ARG VCS_REF=0000000000000000000000000000000000000000
ARG DETAIL_RENDERER_IMAGE=node:24.22.1-alpine@sha256:06d7adf3e0ef61a13f1d28682726366f97a15aa1888c934d3ecec86c33918b53
ARG POSTGRES_CLIENT_IMAGE=postgres:15-alpine@sha256:df7bca0066e6f60cc3dd32faa70caddec20e2c22b58932f79498e5704b23854a
FROM ${BASE_IMAGE} AS base
# Match production PostgreSQL 15; newer pg_dump emits settings PG15 cannot restore.
FROM ${POSTGRES_CLIENT_IMAGE} AS postgres-client
# Fabric's Node renderer has a separate dependency tree and Node runtime.
# The platform's existing Canvas 2 installation remains independent.
FROM ${DETAIL_RENDERER_IMAGE} AS detail-renderer-deps
ARG ALPINE_MIRROR
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache python3 make g++ cairo-dev jpeg-dev pango-dev giflib-dev
WORKDIR /opt/detail-renderer
COPY workers/detail-renderer/package.json workers/detail-renderer/package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm config set registry https://registry.npmmirror.com && CXXFLAGS="-include cstdint" npm_config_build_from_source=canvas npm_config_nodedir=/usr/local npm ci --prefer-offline --no-audit --no-fund
COPY workers/detail-renderer/ ./
RUN chmod -R a+rX /opt/detail-renderer && \
node -e "require('canvas').createCanvas(1,1); console.log('isolated Canvas smoke passed')"
# 安装依赖阶段
FROM base AS deps
ARG ALPINE_MIRROR
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache libc6-compat python3 make g++ cairo-dev jpeg-dev pango-dev giflib-dev openssl
WORKDIR /app
# package-lock.json 是生产构建的必需输入,缺失时 COPY 直接失败。
COPY package.json package-lock.json ./
# 安装依赖(使用淘宝镜像 + BuildKit缓存)
RUN --mount=type=cache,target=/root/.npm \
manifest_sha="$(sha256sum package.json | awk '{print $1}')" && \
lock_sha="$(sha256sum package-lock.json | awk '{print $1}')" && \
echo "Installing dependencies (using cache if available)..." && \
npm config set registry https://registry.npmmirror.com && \
npm_config_build_from_source=canvas npm_config_nodedir=/usr/local npm ci --prefer-offline --no-audit --no-fund --legacy-peer-deps && \
test "$manifest_sha" = "$(sha256sum package.json | awk '{print $1}')" && \
test "$lock_sha" = "$(sha256sum package-lock.json | awk '{print $1}')" && \
node -e "const sharp=require('sharp'); sharp(Buffer.alloc(4),{raw:{width:1,height:1,channels:4}}).png().toBuffer().then(()=>console.log('sharp dependency smoke passed')).catch((error)=>{console.error(error);process.exit(1)})" && \
echo "Dependencies installed ($(du -sh /app/node_modules | cut -f1))"
# File parsers use an unprivileged Landlock/seccomp sandbox inside the default container profile.
FROM base AS performance-preview-sandbox
ARG ALPINE_MIRROR
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && apk add --no-cache build-base linux-headers
COPY workers/performance-preview/sandbox.c /tmp/sandbox.c
RUN cc -O2 -Wall -Wextra -Werror -static /tmp/sandbox.c -o /performance-preview-sandbox
# 本地开发阶段:复用依赖层,并补齐项目运行时会调用的媒体处理工具。
# 源码由 Compose 绑定挂载,避免每次修改代码都重新构建镜像。
FROM deps AS dev
COPY --from=performance-preview-sandbox /performance-preview-sandbox /usr/local/bin/performance-preview-sandbox
ARG ALPINE_MIRROR
RUN apk add --no-cache ffmpeg openssl poppler-utils libreoffice font-noto-cjk
ENV NODE_ENV=development
ENV NEXT_TELEMETRY_DISABLED=1
ENV HOSTNAME=0.0.0.0
EXPOSE 3000
CMD ["npm", "run", "dev", "--", "--hostname", "0.0.0.0"]
# 构建阶段
FROM base AS builder
ARG ALPINE_MIRROR
# 安装构建依赖
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache libc6-compat python3 make g++ cairo-dev jpeg-dev pango-dev giflib-dev ffmpeg openssl
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ARG VCS_REF
# The source revision is immutable image metadata, not a runtime environment
# assertion. Production builds must provide the exact 40-character Git SHA.
RUN if ! printf '%s\n' "$VCS_REF" | grep -Eq '^[0-9a-f]{40}$'; then \
echo "VCS_REF must be the exact 40-character lowercase Git SHA" >&2; \
exit 1; \
fi && \
printf '%s\n' "$VCS_REF" > /app/DEPLOYMENT_COMMIT && \
chmod 0444 /app/DEPLOYMENT_COMMIT
# 品牌资源是页面和 favicon 的离线兜底;缺失或空文件时禁止继续构建。
RUN test -s "/app/public/brand/header-logo.png" && \
test -s "/app/public/brand/login-logo.png" && \
test -s "/app/public/brand/favicon.png" && \
node -e "const sharp=require('sharp'); Promise.all(['header-logo.png','login-logo.png','favicon.png'].map((name)=>sharp('/app/public/brand/'+name,{failOn:'error',limitInputPixels:25000000,animated:false}).rotate().toBuffer())).then(()=>console.log('builder brand image decode smoke passed')).catch((error)=>{console.error(error);process.exit(1)})"
# 动态校验所有 prisma/migrations 子目录均包含非空 migration.sql,避免手工清单漏项或漂移。
RUN node -e "const fs=require('fs'),path=require('path'); const dir='/app/prisma/migrations'; const entries=fs.readdirSync(dir,{withFileTypes:true}).filter(d=>d.isDirectory()); if(entries.length===0) throw new Error('No prisma migrations found'); for(const entry of entries){ const sql=path.join(dir,entry.name,'migration.sql'); const st=fs.statSync(sql); if(!st.isFile()||st.size===0) throw new Error('Missing or empty migration.sql in '+entry.name); } console.log('Verified '+entries.length+' prisma migrations');"
# 这两个动态路由负责兜底访问本地上传文件;如果它们在构建上下文里丢失,
# 线上音频/视频就会直接 404。这里提前失败,避免再把缺路由的镜像发出去。
RUN test -f "/app/app/api/uploads/[...path]/route.ts" && \
test -f "/app/app/uploads/[...path]/route.ts"
# 设置环境变量
ENV NEXT_TELEMETRY_DISABLED=1
# 构建时使用假的环境变量(只用于构建,运行时会被容器的真实环境变量覆盖)
# 这样 Prisma 和其他模块在构建时不会报错
ENV DATABASE_URL="postgresql://build:build@localhost:5432/build"
ENV NEXTAUTH_SECRET="build-time-secret"
ENV NEXTAUTH_URL="http://localhost:3000"
ENV ADMIN_API_KEY="build-time-key"
ENV DINGTALK_CLIENT_ID="build-time-dingtalk-id"
ENV DINGTALK_CLIENT_SECRET="build-time-dingtalk-secret"
# 构建应用(复用 Next.js 构建缓存)
# Next 14 默认按宿主 CPU 数量分配预渲染进程,可能超过容器内存限额。
# 只在构建期间使用一个页面 worker;不改变运行时的 CPU 或业务并发配置。
RUN --mount=type=cache,target=/app/.next/cache \
CIRCLE_NODE_TOTAL=2 NODE_ENV=production npm run build
# 清理 standalone 目录中不需要的文件(减少 1GB+ 体积)
RUN chmod -R a+rX .next/standalone .next/static app public lib prisma scripts && \
echo "清理 standalone 目录..." && \
rm -rf .next/standalone/uploads && \
rm -rf .next/standalone/.build-cache && \
rm -rf .next/standalone/.docker-cache && \
rm -rf .next/standalone/.git && \
rm -rf .next/standalone/__tests__ && \
rm -rf .next/standalone/docs && \
rm -rf .next/standalone/backups && \
rm -rf .next/standalone/.kiro && \
rm -rf .next/standalone/scripts && \
echo "清理完成"
# Install only the migration/backup/seed dependency closure. Its lock is derived
# from the application lock and checked before installation to prevent drift.
FROM base AS migrator-deps
ARG ALPINE_MIRROR
WORKDIR /app
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache openssl
COPY package-lock.json ./package-lock.json
COPY workers/database-migrator/package.json workers/database-migrator/package-lock.json ./workers/database-migrator/
COPY scripts/database-migrator-lock.mjs ./scripts/database-migrator-lock.mjs
RUN node scripts/database-migrator-lock.mjs --check
# The matching generated client is copied from builder; do not generate a second
# client during installation. The CLI engines still run their normal postinstall.
RUN --mount=type=cache,target=/root/.npm \
cd workers/database-migrator && PRISMA_SKIP_POSTINSTALL_GENERATE=1 npm ci --no-audit --no-fund
# Explicit, one-shot database migrator. It is never used by the application
# container or the normal deploy entry. The operator must supply production DB
# identity, exact source SHA and a hashed backup receipt before --apply works.
FROM base AS migrator
ARG ALPINE_MIRROR
WORKDIR /app
ENV NODE_ENV=production
COPY --from=postgres-client /usr/local/bin/pg_dump /usr/local/bin/pg_restore /usr/local/bin/psql /usr/local/bin/
COPY --from=postgres-client /usr/local/lib/libpq.so.5 /usr/local/lib/libpq.so.5
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache openssl krb5-libs libldap libedit zlib && \
command -v openssl >/dev/null && \
pg_dump --version | grep -Eq '^pg_dump \(PostgreSQL\) 15\.' && \
pg_restore --version | grep -Eq '^pg_restore \(PostgreSQL\) 15\.' && \
psql --version | grep -Eq '^psql \(PostgreSQL\) 15\.'
ARG VCS_REF
LABEL org.opencontainers.image.revision=$VCS_REF
COPY --from=migrator-deps --chown=root:root /app/workers/database-migrator/node_modules ./node_modules
COPY --from=builder --chown=root:root /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder --chown=root:root /app/prisma ./prisma
COPY --from=builder --chown=root:root /app/scripts/safe-production-migrate.mjs ./scripts/safe-production-migrate.mjs
COPY --from=builder --chown=root:root /app/scripts/create-verified-production-backup.mjs ./scripts/create-verified-production-backup.mjs
COPY --from=builder --chown=root:root /app/scripts/seed-team-function-config.ts ./scripts/seed-team-function-config.ts
COPY --from=builder --chown=root:root /app/scripts/initialize-personnel-salary-production.ts ./scripts/initialize-personnel-salary-production.ts
COPY --from=builder --chown=root:root /app/scripts/maintain-salary-performance-versions.ts ./scripts/maintain-salary-performance-versions.ts
COPY --from=builder --chown=root:root /app/lib/personnel-salary.ts /app/lib/personnel-salary-contract.ts /app/lib/performance-salary-access.ts /app/lib/salary-organization-department.ts ./lib/
COPY --from=builder --chown=root:root /app/lib/salary-position-seeds.ts /app/lib/salary-position-contract.ts /app/lib/salary-market-intent-contract.ts ./lib/
# Source closure for the team-function seed; no application routes or services.
COPY --from=builder --chown=root:root /app/lib/auto-personnel-rules.ts /app/lib/organization-material-permissions.ts /app/lib/prisma.ts /app/lib/team-function-contract.ts /app/lib/department-permission.ts /app/lib/employee-directory.ts /app/lib/env-validation.ts /app/lib/material-type-mapper.ts /app/lib/material-type-options.ts /app/lib/permission-groups.ts /app/lib/team-functions.ts /app/lib/user-permission-inherit.ts /app/lib/video-material-types.ts /app/lib/xiaoyi-delivery-material.ts ./lib/
COPY --from=builder --chown=root:root /app/tsconfig.json ./tsconfig.json
COPY --from=builder --chown=root:root /app/data/team-function-initial-content.json ./data/team-function-initial-content.json
COPY --from=builder --chown=root:root /app/DEPLOYMENT_COMMIT /app/DEPLOYMENT_COMMIT
RUN test "$(cat /app/DEPLOYMENT_COMMIT)" = "$VCS_REF" && \
test -x /app/node_modules/prisma/node_modules/@prisma/engines/schema-engine-linux-musl-openssl-3.0.x && \
test "$(stat -c '%a' /app/DEPLOYMENT_COMMIT)" = 444
USER node
# Prove the CLI can use the bundled native engine without downloading or writing.
RUN --network=none ./node_modules/.bin/prisma -v
ENTRYPOINT ["node", "scripts/safe-production-migrate.mjs"]
# 生产运行阶段
FROM base AS runner
COPY --from=performance-preview-sandbox /performance-preview-sandbox /usr/local/bin/performance-preview-sandbox
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ARG ALPINE_MIRROR
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache ffmpeg python3 cairo jpeg pango giflib openssl poppler-utils flock libreoffice font-noto-cjk && \
command -v flock >/dev/null && \
flock --exclusive --timeout 1 --conflict-exit-code 75 --no-fork \
/tmp/material-upload-flock-probe.lock sh -c 'true' && \
rm -f /tmp/material-upload-flock-probe.lock
ARG VCS_REF
LABEL org.opencontainers.image.revision=$VCS_REF
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 --ingroup nodejs nextjs
RUN mkdir -p /app/scripts
# 复制必要文件
COPY --from=builder --chown=root:root /app/.next/standalone ./
COPY --from=builder --chown=root:root /app/.next/static ./.next/static
COPY --from=builder --chown=root:root /app/app ./app
COPY --from=builder --chown=root:root /app/public ./public
COPY --from=builder --chown=root:root /app/DEPLOYMENT_COMMIT /app/DEPLOYMENT_COMMIT
COPY --from=detail-renderer-deps --chown=root:root /opt/detail-renderer /opt/detail-renderer
COPY --from=detail-renderer-deps --chown=root:root /usr/local/bin/node /opt/detail-renderer/bin/node
ENV DETAIL_RENDERER_NODE=/opt/detail-renderer/bin/node
ENV DETAIL_RENDERER_ENTRY=/opt/detail-renderer/cli.mjs
# 只复制运行时必需的 node_modules
COPY --from=builder --chown=root:root /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder --chown=root:root /app/node_modules/ag-psd ./node_modules/ag-psd
COPY --from=builder --chown=root:root /app/node_modules/ioredis ./node_modules/ioredis
COPY --from=builder --chown=root:root /app/node_modules/@ioredis ./node_modules/@ioredis
COPY --from=builder --chown=root:root /app/node_modules/@aws-sdk ./node_modules/@aws-sdk
COPY --from=builder --chown=root:root /app/node_modules/@smithy ./node_modules/@smithy
# 复制运行时 schema 与全部 migration(动态对齐 prisma/migrations,避免手工清单漏项);仍不复制 engine-cache。
COPY --from=builder --chown=root:root /app/prisma/schema.prisma ./prisma/schema.prisma
COPY --from=builder --chown=root:root /app/prisma/migrations ./prisma/migrations
COPY --from=builder --chown=root:root /app/lib ./lib
COPY --from=builder --chown=root:root /app/scripts/public-traffic-rollup-from-nginx.py ./scripts/public-traffic-rollup-from-nginx.py
COPY --from=builder --chown=root:root /app/scripts/collapse-performance-survey-template-versions.mjs ./scripts/collapse-performance-survey-template-versions.mjs
COPY --from=builder --chown=root:root /app/scripts/backfill-art-workflow-planner-owner.mjs ./scripts/backfill-art-workflow-planner-owner.mjs
COPY --from=builder --chown=root:root /app/scripts/backfill-salary-departments.ts ./scripts/backfill-salary-departments.ts
COPY --from=builder --chown=root:root /app/scripts/safe-production-migrate.mjs /app/scripts/create-verified-production-backup.mjs /app/scripts/salary-grade-configuration.cjs /app/scripts/maintain-salary-grade-configuration.cjs ./scripts/
# 代码在 COPY 时直接归 root,避免再次改动整棵目录产生重复镜像层。
# 仅运行时缓存和存储目录允许 nextjs 写入,代码权限保持只读。
RUN install -d -o nextjs -g nodejs -m 0755 /app/.next/cache && \
install -d -o nextjs -g nodejs -m 0750 /app/uploads /app/uploads/temp /app/uploads/assembled /app/uploads/materials /app/uploads/cleanup && \
install -d -o nextjs -g nodejs -m 0700 /app/detail-generator-private && \
test "$(cat /app/DEPLOYMENT_COMMIT)" = "$VCS_REF" && \
test "$(stat -c '%a' /app/DEPLOYMENT_COMMIT)" = 444 && \
test -s /app/public/brand/header-logo.png && \
test -s /app/public/brand/login-logo.png && \
test -s /app/public/brand/favicon.png
USER nextjs
RUN node -e "const fs=require('fs'); fs.readdirSync('/app/public/brand'); fs.readdirSync('/app/public/detail-generator/fonts'); for(const file of ['lib/desktop-client/contract.mjs','prisma/schema.prisma','lib/url-rewrite.ts','lib/proxy-media-security.ts','app/api/proxy-media/route.ts','lib/s3.ts','lib/network-detection.ts'])fs.readFileSync('/app/'+file); fs.accessSync('/opt/detail-renderer/cli.mjs',fs.constants.R_OK); const sharp=require('sharp'); Promise.all(['header-logo.png','login-logo.png','favicon.png'].map((name)=>sharp('/app/public/brand/'+name,{failOn:'error',limitInputPixels:25000000,animated:false}).rotate().toBuffer())).then(()=>console.log('runner brand image decode smoke passed')).catch((error)=>{console.error(error);process.exit(1)})"
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]