refacotr: 重构部署实现,不每次都重新构建镜像,只在第一次构建,后面只将编译产物放入挂载目录重启容器

This commit is contained in:
ah--desktop
2026-07-12 17:13:45 +08:00
parent 7a2498cef2
commit b9a75af67c
13 changed files with 523 additions and 130 deletions
+17 -43
View File
@@ -1,67 +1,41 @@
import { execSync } from 'child_process';
import { writeFileSync, readFileSync, existsSync } from 'fs';
import { existsSync } from 'fs';
import { join } from 'path';
import { Client } from 'ssh2';
import { getBackendDir, getBackendDeployDir } from '../config.js';
import { findMainJar, getLocalTempPath, resolveMavenCommand } from '../platform.js';
import { uploadFile, ensureRemoteDir } from '../ssh.js';
import { remoteBuildImage } from '../docker.js';
import { syncBackendArtifact } from '../artifacts.js';
import { getArtifactDir, getBackendDir, getRemoteDataDir } from '../config.js';
import { findMainJar, resolveMavenCommand } from '../platform.js';
import { ensureRemoteDir, uploadFile } from '../ssh.js';
import { printInfo, printSuccess } from '../ui/render.js';
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
export const serviceType: Service = 'backend';
export async function build(cfg: ServiceEnvConfig): Promise<string> {
export async function build(_cfg: ServiceEnvConfig): Promise<string> {
const backendDir = getBackendDir();
if (!existsSync(backendDir)) throw new Error(`后端项目目录不存在: ${backendDir}`);
const mvnCmd = resolveMavenCommand(backendDir);
printInfo('构建后端 (Maven)...');
// Spring profile 在容器启动时注入,Maven 构建不使用 -P
execSync(`${mvnCmd} clean package -DskipTests`, {
stdio: 'inherit',
cwd: backendDir,
// @types/node 22 中 shell 仅接受 string,Windows 需指定 cmd 才能执行 .cmd
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
});
printSuccess('后端构建完成');
const jarDir = join(backendDir, 'target');
if (!existsSync(jarDir)) throw new Error(`构建产物目录不存在: ${jarDir}`);
return jarDir;
const jarPath = findMainJar(join(backendDir, 'target'));
const artifactDir = syncBackendArtifact(jarPath);
printSuccess(`后端构建完成,产物: ${artifactDir}/app.jar`);
return artifactDir;
}
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, env: Environment): Promise<void> {
const serviceDir = `${cfg.server.deployPath}/backend`;
await ensureRemoteDir(conn, serviceDir);
const jarPath = findMainJar(buildDir);
await uploadFile(conn, jarPath, `${serviceDir}/app.jar`);
const dockerfileTmp = getLocalTempPath('ecom-backend.Dockerfile');
const dockerfileSrc = join(getBackendDeployDir(), 'Dockerfile');
if (!existsSync(dockerfileSrc)) {
printInfo('后端 deploy/Dockerfile 不存在,使用默认模板');
writeFileSync(dockerfileTmp, [
'# 默认使用 DaoCloud 镜像加速,服务器可访问 Docker Hub 时改为 eclipse-temurin:17-jre-alpine',
'ARG BASE_IMAGE=docker.m.daocloud.io/library/eclipse-temurin:17-jre-alpine',
'FROM ${BASE_IMAGE}',
'WORKDIR /app',
'RUN addgroup -S app && adduser -S app -G app',
'COPY app.jar app.jar',
'RUN chown -R app:app /app',
'USER app',
'# 实际端口由 Spring profile 决定(test:8101 / pre:8102 / prod:8103)',
'EXPOSE 8101 8102 8103',
'ENTRYPOINT ["java", "-jar", "app.jar"]',
'',
].join('\n'));
} else {
writeFileSync(dockerfileTmp, readFileSync(dockerfileSrc, 'utf8'));
}
await uploadFile(conn, dockerfileTmp, `${serviceDir}/Dockerfile`);
await remoteBuildImage(conn, 'backend', serviceDir, env);
/** 上传 artifacts/backend 到远程挂载目录 */
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, _env: Environment): Promise<void> {
const artifactDir = getArtifactDir('backend');
const remoteDataDir = getRemoteDataDir(cfg, 'backend');
await ensureRemoteDir(conn, remoteDataDir);
await uploadFile(conn, join(artifactDir, 'app.jar'), `${remoteDataDir}/app.jar`);
printSuccess(`后端产物已上传到 ${remoteDataDir}`);
}
+9 -3
View File
@@ -3,7 +3,8 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { Client } from 'ssh2';
import { getFrontendDir } from '../config.js';
import { syncFrontendArtifacts } from '../artifacts.js';
import { getArtifactDir, getFrontendDir } from '../config.js';
import { createTarGz, getLocalTempPath } from '../platform.js';
import { execRemote, uploadFile, ensureRemoteDir } from '../ssh.js';
import { printInfo, printSuccess } from '../ui/render.js';
@@ -21,10 +22,15 @@ export async function build(): Promise<string> {
const distDir = join(frontendDir, 'apps', 'web-antd', 'dist');
if (!existsSync(distDir)) throw new Error(`构建产物目录不存在: ${distDir}`);
return distDir;
const artifactDir = syncFrontendArtifacts(distDir);
printSuccess(`前端产物: ${artifactDir}`);
return artifactDir;
}
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, _env: Environment): Promise<void> {
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, _env: Environment): Promise<void> {
const buildDir = getArtifactDir('frontend');
if (cfg.extractDir) {
await ensureRemoteDir(conn, cfg.extractDir);
+76 -12
View File
@@ -1,6 +1,16 @@
import { connectWithRetry, installKeyAfterPasswordAuth, execRemote } from '../ssh.js';
import { composeDeploy, composeRestart, composeLogs, composeStatus, composeDown, uploadComposeFile } from '../docker.js';
import { loadConfig, getServiceConfig, syncServerKeyAuth } from '../config.js';
import {
composeRestartAfterUpload,
initServiceRuntime,
remoteImageExists,
uploadComposeFile,
composeRestart,
composeLogs,
composeStatus,
composeDown,
} from '../docker.js';
import { assertArtifactsExist, ensureArtifactsDirs } from '../artifacts.js';
import { getArtifactDir, loadConfig, getServiceConfig, syncServerKeyAuth } from '../config.js';
import { printError, printInfo, printSuccess } from '../ui/render.js';
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
@@ -18,11 +28,12 @@ const deployers: Record<Service, {
};
export async function buildService(service: Service, cfg: ServiceEnvConfig): Promise<string> {
ensureArtifactsDirs();
const deployer = deployers[service];
if (!deployer) throw new Error(`未知服务: ${service}`);
printInfo(`构建 ${service}...`);
const buildDir = await deployer.build(cfg);
printSuccess(`${service} 构建完成`);
printSuccess(`${service} 构建完成 → ${getArtifactDir(service)}`);
return buildDir;
}
@@ -39,7 +50,7 @@ export async function deployService(
await deployer.deploy(conn, cfg, buildDir, env);
}
/** 连接 SSH;密码登录成功后自动安装公钥并持久化到 config.json */
/** 连接 SSH;密码登录成功后自动安装公钥 */
async function connectForService(
cfg: ServiceEnvConfig,
onPassword?: () => Promise<string>,
@@ -62,18 +73,41 @@ async function connectForService(
return conn;
}
export async function buildAndDeployServices(
/** Docker 服务:上传产物后,首次 init 镜像,后续仅重启 */
async function finishDockerDeploy(conn: any, service: Service, cfg: ServiceEnvConfig, env: Environment): Promise<void> {
const exists = await remoteImageExists(conn, service, env);
if (!exists) {
await initServiceRuntime(conn, service, cfg, env);
} else {
await uploadComposeFile(conn, service, cfg, env);
await composeRestartAfterUpload(conn, cfg, service, env);
}
}
/** 仅编译到 artifacts/,不上传 */
export async function buildServicesOnly(services: Service[]): Promise<void> {
ensureArtifactsDirs();
for (const service of services) {
const config = await loadConfig();
const cfg = getServiceConfig(config, service);
console.clear();
await buildService(service, cfg);
}
}
/** 从 artifacts/ 上传并重启(不编译) */
export async function deployArtifactsOnly(
services: Service[],
onPassword?: (service: Service) => Promise<string>,
): Promise<void> {
ensureArtifactsDirs();
for (const service of services) {
assertArtifactsExist(service);
const config = await loadConfig();
const env = config.currentEnv;
const cfg = getServiceConfig(config, service, env);
console.clear();
const buildDir = await buildService(service, cfg);
// 若同 host 已配置密钥,connectWithRetry 会直接免密,不再触发 onPassword
const conn = await connectForService(
cfg,
onPassword ? () => onPassword(service) : undefined,
@@ -81,12 +115,42 @@ export async function buildAndDeployServices(
try {
if (cfg.extractDir) {
await deployService(conn, service, cfg, buildDir, env);
await deployService(conn, service, cfg, getArtifactDir(service), env);
} else {
await uploadComposeFile(conn, service, cfg, env);
await deployService(conn, service, cfg, buildDir, env);
// 镜像重建后强制 recreate,否则 :latest 内容变了容器也不会换
await composeDeploy(conn, cfg, service, env);
await deployService(conn, service, cfg, getArtifactDir(service), env);
await finishDockerDeploy(conn, service, cfg, env);
}
} finally {
conn.end();
}
printSuccess(`${service} 产物已上传并重启`);
}
}
/** 自动部署:编译 → 上传 → 重启(不重建镜像) */
export async function buildAndDeployServices(
services: Service[],
onPassword?: (service: Service) => Promise<string>,
): Promise<void> {
ensureArtifactsDirs();
for (const service of services) {
const config = await loadConfig();
const env = config.currentEnv;
const cfg = getServiceConfig(config, service, env);
console.clear();
await buildService(service, cfg);
const conn = await connectForService(
cfg,
onPassword ? () => onPassword(service) : undefined,
);
try {
if (cfg.extractDir) {
await deployService(conn, service, cfg, getArtifactDir(service), env);
} else {
await deployService(conn, service, cfg, getArtifactDir(service), env);
await finishDockerDeploy(conn, service, cfg, env);
}
} finally {
conn.end();
+26 -30
View File
@@ -1,12 +1,12 @@
import { execSync } from 'child_process';
import { writeFileSync, readFileSync, existsSync, mkdirSync, rmSync } from 'fs';
import { existsSync, mkdirSync, rmSync } from 'fs';
import { join } from 'path';
import { Client } from 'ssh2';
import { getLicenseDir, getLicenseDeployDir } from '../config.js';
import { copyBuildArtifacts, createTarGz, getLocalTempPath } from '../platform.js';
import { execRemote, uploadFile, ensureRemoteDir } from '../ssh.js';
import { remoteBuildImage } from '../docker.js';
import { syncLicenseArtifacts, uploadArtifactDirectory } from '../artifacts.js';
import { getArtifactDir, getLicenseDir, getRemoteDataDir } from '../config.js';
import { copyBuildArtifacts, getLocalTempPath } from '../platform.js';
import { ensureRemoteDir } from '../ssh.js';
import { printInfo, printSuccess } from '../ui/render.js';
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
@@ -19,8 +19,8 @@ export async function build(): Promise<string> {
printInfo('构建许可证 (NestJS)...');
execSync('pnpm install && pnpm build', { stdio: 'inherit', cwd: serverDir });
printSuccess('许可证构建完成');
// 先收集到临时目录,再同步到 artifacts/license
const tmpDir = getLocalTempPath('ecom-license-build');
if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true });
mkdirSync(tmpDir, { recursive: true });
@@ -31,30 +31,26 @@ export async function build(): Promise<string> {
copyBuildArtifacts(join(serverDir, 'keys'), join(tmpDir, 'keys'), { optional: true });
copyBuildArtifacts(join(serverDir, '.env'), join(tmpDir, '.env'), { optional: true });
return tmpDir;
const artifactDir = syncLicenseArtifacts(tmpDir);
rmSync(tmpDir, { recursive: true, force: true });
// 本地安装生产依赖,一并打入产物目录
printInfo('安装许可证生产依赖...');
execSync('corepack enable && pnpm install --prod --frozen-lockfile', {
stdio: 'inherit',
cwd: artifactDir,
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
});
printSuccess(`许可证构建完成,产物: ${artifactDir}`);
return artifactDir;
}
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, env: Environment): Promise<void> {
const serviceDir = `${cfg.server.deployPath}/license`;
await ensureRemoteDir(conn, serviceDir);
const tmpTar = getLocalTempPath('ecom-license-build.tar.gz');
createTarGz(buildDir, tmpTar);
const dockerfileTmp = getLocalTempPath('ecom-license.Dockerfile');
const dockerfileSrc = join(getLicenseDeployDir(), 'Dockerfile');
if (!existsSync(dockerfileSrc)) {
printInfo('许可证 deploy/Dockerfile 不存在,使用默认模板');
writeFileSync(dockerfileTmp, 'FROM node:22-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY package.json pnpm-lock.yaml ./\nRUN corepack enable && pnpm install --prod --frozen-lockfile 2>/dev/null; exit 0\nCOPY dist ./dist\nCOPY keys ./keys\nCOPY .env ./.env\nRUN chown -R app:app /app\nUSER app\nEXPOSE 3100\nCMD ["node", "dist/main.js"]\n');
} else {
writeFileSync(dockerfileTmp, readFileSync(dockerfileSrc, 'utf8'));
}
await uploadFile(conn, tmpTar, `${serviceDir}/build.tar.gz`);
await uploadFile(conn, dockerfileTmp, `${serviceDir}/Dockerfile`);
const { code, stderr } = await execRemote(conn, `cd "${serviceDir}" && tar -xzf build.tar.gz && rm build.tar.gz`);
if (code !== 0) throw new Error(`解压失败: ${stderr}`);
await remoteBuildImage(conn, 'license', serviceDir, env);
/** 上传 artifacts/license 到远程挂载目录 */
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, _env: Environment): Promise<void> {
const artifactDir = getArtifactDir('license');
const remoteDataDir = getRemoteDataDir(cfg, 'license');
await ensureRemoteDir(conn, remoteDataDir);
await uploadArtifactDirectory(conn, artifactDir, remoteDataDir);
printSuccess(`许可证产物已上传到 ${remoteDataDir}`);
}