mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 04:29:21 +08:00
feat: 完善部署脚本
This commit is contained in:
@@ -12,7 +12,7 @@
|
||||
"port": 80,
|
||||
"extractDir": "/var/www/ecom-frontend"
|
||||
},
|
||||
"production": {
|
||||
"prod": {
|
||||
"server": { "host": "frontend.prod.com", "port": 22, "username": "root", "deployPath": "/var/www/ecom-frontend", "authType": "password" },
|
||||
"port": 80,
|
||||
"extractDir": "/var/www/ecom-frontend"
|
||||
@@ -21,21 +21,21 @@
|
||||
"backend": {
|
||||
"test": {
|
||||
"server": { "host": "192.168.3.100", "port": 22, "username": "root", "deployPath": "/opt/ecom-backend", "authType": "password" },
|
||||
"port": 8080,
|
||||
"port": 8101,
|
||||
"springProfile": "test",
|
||||
"dbUrl": "",
|
||||
"redisUrl": ""
|
||||
},
|
||||
"pre": {
|
||||
"server": { "host": "192.168.3.100", "port": 22, "username": "root", "deployPath": "/opt/ecom-backend", "authType": "password" },
|
||||
"port": 8080,
|
||||
"springProfile": "staging",
|
||||
"port": 8102,
|
||||
"springProfile": "pre",
|
||||
"dbUrl": "",
|
||||
"redisUrl": ""
|
||||
},
|
||||
"production": {
|
||||
"prod": {
|
||||
"server": { "host": "backend.prod.com", "port": 22, "username": "root", "deployPath": "/opt/ecom-backend", "authType": "password" },
|
||||
"port": 8080,
|
||||
"port": 8103,
|
||||
"springProfile": "prod",
|
||||
"dbUrl": "",
|
||||
"redisUrl": ""
|
||||
@@ -54,10 +54,10 @@
|
||||
"nodeEnv": "pre",
|
||||
"licenseDbUrl": ""
|
||||
},
|
||||
"production": {
|
||||
"prod": {
|
||||
"server": { "host": "license.prod.com", "port": 22, "username": "root", "deployPath": "/opt/ecom-license", "authType": "password" },
|
||||
"port": 3100,
|
||||
"nodeEnv": "production",
|
||||
"nodeEnv": "prod",
|
||||
"licenseDbUrl": ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,17 +29,17 @@ function defaultConfig(): DeployConfig {
|
||||
frontend: {
|
||||
test: defaultServiceConfig('192.168.1.100', 80, '/var/www/ecom-frontend'),
|
||||
pre: defaultServiceConfig('192.168.1.101', 80, '/var/www/ecom-frontend'),
|
||||
production: defaultServiceConfig('frontend.prod.com', 80, '/var/www/ecom-frontend'),
|
||||
prod: defaultServiceConfig('frontend.prod.com', 80, '/var/www/ecom-frontend'),
|
||||
},
|
||||
backend: {
|
||||
test: { ...defaultServiceConfig('192.168.1.100', 8080), springProfile: 'test', dbUrl: '', redisUrl: '' },
|
||||
pre: { ...defaultServiceConfig('192.168.1.101', 8080), springProfile: 'pre', dbUrl: '', redisUrl: '' },
|
||||
production: { ...defaultServiceConfig('backend.prod.com', 8080), springProfile: 'prod', dbUrl: '', redisUrl: '' },
|
||||
test: { ...defaultServiceConfig('192.168.1.100', 8101), springProfile: 'test', dbUrl: '', redisUrl: '' },
|
||||
pre: { ...defaultServiceConfig('192.168.1.101', 8102), springProfile: 'pre', dbUrl: '', redisUrl: '' },
|
||||
prod: { ...defaultServiceConfig('backend.prod.com', 8103), springProfile: 'prod', dbUrl: '', redisUrl: '' },
|
||||
},
|
||||
license: {
|
||||
test: { ...defaultServiceConfig('192.168.1.100', 3100), nodeEnv: 'test', licenseDbUrl: '' },
|
||||
pre: { ...defaultServiceConfig('192.168.1.101', 3100), nodeEnv: 'pre', licenseDbUrl: '' },
|
||||
production: { ...defaultServiceConfig('license.prod.com', 3100), nodeEnv: 'production', licenseDbUrl: '' },
|
||||
prod: { ...defaultServiceConfig('license.prod.com', 3100), nodeEnv: 'prod', licenseDbUrl: '' },
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -90,12 +90,40 @@ export function getConfigPath(): string {
|
||||
return CONFIG_PATH;
|
||||
}
|
||||
|
||||
/** 部署环境 pre 对应 Spring profile staging */
|
||||
/** 与 application-{profile}.yml 中 server.port 保持一致 */
|
||||
export function resolveBackendPort(env: Environment): number {
|
||||
switch (env) {
|
||||
case 'test':
|
||||
return 8101;
|
||||
case 'pre':
|
||||
return 8102;
|
||||
case 'prod':
|
||||
return 8103;
|
||||
}
|
||||
}
|
||||
|
||||
/** 部署环境 pre 对应 Spring profile pre(application-pre.yml) */
|
||||
export function resolveSpringProfile(profile?: string): string {
|
||||
if (profile === 'pre') return 'staging';
|
||||
return profile || 'prod';
|
||||
}
|
||||
|
||||
/** 部署环境后缀:test / pre / prod */
|
||||
export function resolveEnvSuffix(env: Environment): string {
|
||||
return env;
|
||||
}
|
||||
|
||||
/** Docker 镜像、容器、Compose 服务/项目名(含环境后缀) */
|
||||
export function getDockerResourceNames(service: Service, env: Environment) {
|
||||
const suffix = resolveEnvSuffix(env);
|
||||
const base = `ecom-${service}-${suffix}`;
|
||||
return {
|
||||
composeService: base,
|
||||
containerName: base,
|
||||
imageTag: `${base}:latest`,
|
||||
composeProject: base,
|
||||
};
|
||||
}
|
||||
|
||||
/** 同一 host+username 的服务共享 SSH 密钥配置 */
|
||||
export async function syncServerKeyAuth(
|
||||
host: string,
|
||||
|
||||
@@ -4,10 +4,11 @@ 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 { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from '../types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'backend';
|
||||
|
||||
@@ -15,13 +16,15 @@ export async function build(cfg: ServiceEnvConfig): Promise<string> {
|
||||
const backendDir = getBackendDir();
|
||||
if (!existsSync(backendDir)) throw new Error(`后端项目目录不存在: ${backendDir}`);
|
||||
|
||||
const mvnw = join(backendDir, 'mvnw');
|
||||
const mvnCmd = existsSync(mvnw) ? `"${mvnw}"` : 'mvn';
|
||||
const mvnCmd = resolveMavenCommand(backendDir);
|
||||
|
||||
printInfo('构建后端 (Maven)...');
|
||||
// Spring profile 在容器启动时注入,Maven 构建不使用 -P
|
||||
execSync(`${mvnCmd} clean package -DskipTests`, {
|
||||
stdio: 'inherit', cwd: backendDir,
|
||||
stdio: 'inherit',
|
||||
cwd: backendDir,
|
||||
// @types/node 22 中 shell 仅接受 string,Windows 需指定 cmd 才能执行 .cmd
|
||||
shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined,
|
||||
});
|
||||
printSuccess('后端构建完成');
|
||||
|
||||
@@ -30,23 +33,35 @@ export async function build(cfg: ServiceEnvConfig): Promise<string> {
|
||||
return jarDir;
|
||||
}
|
||||
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
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 jars = execSync(`ls "${buildDir}"/*.jar 2>/dev/null`, { encoding: 'utf8' }).trim();
|
||||
if (!jars) throw new Error('未找到 JAR 文件');
|
||||
|
||||
await uploadFile(conn, jars.split('\n')[0], `${serviceDir}/app.jar`);
|
||||
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('/tmp/ecom-backend.Dockerfile', 'FROM eclipse-temurin:17-jre-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY app.jar app.jar\nRUN chown -R app:app /app\nUSER app\nEXPOSE 8080\nENTRYPOINT ["java", "-jar", "app.jar"]\n');
|
||||
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('/tmp/ecom-backend.Dockerfile', readFileSync(dockerfileSrc, 'utf8'));
|
||||
writeFileSync(dockerfileTmp, readFileSync(dockerfileSrc, 'utf8'));
|
||||
}
|
||||
await uploadFile(conn, '/tmp/ecom-backend.Dockerfile', `${serviceDir}/Dockerfile`);
|
||||
await uploadFile(conn, dockerfileTmp, `${serviceDir}/Dockerfile`);
|
||||
|
||||
await remoteBuildImage(conn, 'backend', serviceDir);
|
||||
await remoteBuildImage(conn, 'backend', serviceDir, env);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { getFrontendDir } from '../config.js';
|
||||
import { createTarGz, getLocalTempPath } from '../platform.js';
|
||||
import { execRemote, uploadFile, ensureRemoteDir } from '../ssh.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from '../types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'frontend';
|
||||
|
||||
@@ -23,16 +24,12 @@ export async function build(): Promise<string> {
|
||||
return distDir;
|
||||
}
|
||||
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string, _env: Environment): Promise<void> {
|
||||
if (cfg.extractDir) {
|
||||
await ensureRemoteDir(conn, cfg.extractDir);
|
||||
|
||||
const tmpTar = '/tmp/ecom-frontend-build.tar.gz';
|
||||
try {
|
||||
execSync(`tar -czf "${tmpTar}" -C "${buildDir}" .`, { stdio: 'pipe' });
|
||||
} catch (e: any) {
|
||||
throw new Error(`打包失败 (${buildDir}): ${e.message}`);
|
||||
}
|
||||
const tmpTar = getLocalTempPath('ecom-frontend-build.tar.gz');
|
||||
createTarGz(buildDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, `${cfg.extractDir}/frontend.tar.gz`);
|
||||
|
||||
const { code, stderr } = await execRemote(
|
||||
@@ -47,8 +44,8 @@ export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: stri
|
||||
const serviceDir = `${cfg.server.deployPath}/frontend`;
|
||||
await ensureRemoteDir(conn, serviceDir);
|
||||
|
||||
const tmpTar = '/tmp/ecom-frontend-build.tar.gz';
|
||||
execSync(`tar -czf "${tmpTar}" -C "${buildDir}" .`, { stdio: 'pipe' });
|
||||
const tmpTar = getLocalTempPath('ecom-frontend-build.tar.gz');
|
||||
createTarGz(buildDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, `${serviceDir}/build.tar.gz`);
|
||||
|
||||
const { code, stderr } = await execRemote(conn, `cd "${serviceDir}" && tar -xzf build.tar.gz && rm build.tar.gz`);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { connectWithRetry, installKeyAfterPasswordAuth, execRemote } from '../ssh.js';
|
||||
import { composeUp, composeRestart, composeLogs, composeStatus, composeDown, uploadComposeFile } from '../docker.js';
|
||||
import { composeDeploy, composeRestart, composeLogs, composeStatus, composeDown, uploadComposeFile } from '../docker.js';
|
||||
import { loadConfig, getServiceConfig, syncServerKeyAuth } from '../config.js';
|
||||
import { printError, printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
@@ -8,7 +8,10 @@ import * as frontendDeploy from './frontend.js';
|
||||
import * as backendDeploy from './backend.js';
|
||||
import * as licenseDeploy from './license.js';
|
||||
|
||||
const deployers: Record<Service, { build: (cfg?: ServiceEnvConfig) => Promise<string>; deploy: (conn: any, cfg: ServiceEnvConfig, buildDir: string) => Promise<void> }> = {
|
||||
const deployers: Record<Service, {
|
||||
build: (cfg?: ServiceEnvConfig) => Promise<string>;
|
||||
deploy: (conn: any, cfg: ServiceEnvConfig, buildDir: string, env: Environment) => Promise<void>;
|
||||
}> = {
|
||||
frontend: frontendDeploy as any,
|
||||
backend: backendDeploy as any,
|
||||
license: licenseDeploy as any,
|
||||
@@ -23,11 +26,17 @@ export async function buildService(service: Service, cfg: ServiceEnvConfig): Pro
|
||||
return buildDir;
|
||||
}
|
||||
|
||||
export async function deployService(conn: any, service: Service, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
export async function deployService(
|
||||
conn: any,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
buildDir: string,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const deployer = deployers[service];
|
||||
if (!deployer) throw new Error(`未知服务: ${service}`);
|
||||
printInfo(`部署 ${service} 到 ${cfg.server.host}...`);
|
||||
await deployer.deploy(conn, cfg, buildDir);
|
||||
await deployer.deploy(conn, cfg, buildDir, env);
|
||||
}
|
||||
|
||||
/** 连接 SSH;密码登录成功后自动安装公钥并持久化到 config.json */
|
||||
@@ -59,7 +68,8 @@ export async function buildAndDeployServices(
|
||||
): Promise<void> {
|
||||
for (const service of services) {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
console.clear();
|
||||
const buildDir = await buildService(service, cfg);
|
||||
|
||||
@@ -71,11 +81,12 @@ export async function buildAndDeployServices(
|
||||
|
||||
try {
|
||||
if (cfg.extractDir) {
|
||||
await deployService(conn, service, cfg, buildDir);
|
||||
await deployService(conn, service, cfg, buildDir, env);
|
||||
} else {
|
||||
await uploadComposeFile(conn, service, cfg);
|
||||
await deployService(conn, service, cfg, buildDir);
|
||||
await composeUp(conn, cfg, service);
|
||||
await uploadComposeFile(conn, service, cfg, env);
|
||||
await deployService(conn, service, cfg, buildDir, env);
|
||||
// 镜像重建后强制 recreate,否则 :latest 内容变了容器也不会换
|
||||
await composeDeploy(conn, cfg, service, env);
|
||||
}
|
||||
} finally {
|
||||
conn.end();
|
||||
@@ -86,35 +97,40 @@ export async function buildAndDeployServices(
|
||||
|
||||
export async function restartService(service: Service, onPassword?: () => Promise<string>): Promise<void> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { await composeRestart(conn, cfg, service); } finally { conn.end(); }
|
||||
try { await composeRestart(conn, cfg, service, env); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function stopService(service: Service, onPassword?: () => Promise<string>): Promise<void> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { await composeDown(conn, cfg, service); } finally { conn.end(); }
|
||||
try { await composeDown(conn, cfg, service, env); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function serviceLogs(service: Service, tail = 50, onPassword?: () => Promise<string>): Promise<string> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { return await composeLogs(conn, cfg, service, tail); } finally { conn.end(); }
|
||||
try { return await composeLogs(conn, cfg, service, env, tail); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function serviceStatus(service: Service, onPassword?: () => Promise<string>): Promise<string> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try { return await composeStatus(conn, cfg); } finally { conn.end(); }
|
||||
try { return await composeStatus(conn, cfg, service, env); } finally { conn.end(); }
|
||||
}
|
||||
|
||||
export async function checkRemoteDocker(service: Service, onPassword?: () => Promise<string>): Promise<boolean> {
|
||||
const config = await loadConfig();
|
||||
const cfg = getServiceConfig(config, service);
|
||||
const env = config.currentEnv;
|
||||
const cfg = getServiceConfig(config, service, env);
|
||||
try {
|
||||
const conn = await connectForService(cfg, onPassword);
|
||||
try {
|
||||
|
||||
@@ -4,10 +4,11 @@ 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 { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from '../types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
export const serviceType: Service = 'license';
|
||||
|
||||
@@ -20,39 +21,40 @@ export async function build(): Promise<string> {
|
||||
execSync('pnpm install && pnpm build', { stdio: 'inherit', cwd: serverDir });
|
||||
printSuccess('许可证构建完成');
|
||||
|
||||
const tmpDir = '/tmp/ecom-license-build';
|
||||
const tmpDir = getLocalTempPath('ecom-license-build');
|
||||
if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true });
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
execSync(`cp -r "${serverDir}/dist" "${tmpDir}/dist"`, { stdio: 'pipe' });
|
||||
execSync(`cp "${serverDir}/package.json" "${tmpDir}/"`, { stdio: 'pipe' });
|
||||
execSync(`cp "${serverDir}/pnpm-lock.yaml" "${tmpDir}/" 2>/dev/null || true`, { stdio: 'pipe' });
|
||||
if (existsSync(join(serverDir, 'keys'))) execSync(`cp -r "${serverDir}/keys" "${tmpDir}/keys"`, { stdio: 'pipe' });
|
||||
execSync(`cp "${serverDir}/.env" "${tmpDir}/.env" 2>/dev/null || true`, { stdio: 'pipe' });
|
||||
copyBuildArtifacts(join(serverDir, 'dist'), join(tmpDir, 'dist'));
|
||||
copyBuildArtifacts(join(serverDir, 'package.json'), join(tmpDir, 'package.json'));
|
||||
copyBuildArtifacts(join(serverDir, 'pnpm-lock.yaml'), join(tmpDir, 'pnpm-lock.yaml'), { optional: true });
|
||||
copyBuildArtifacts(join(serverDir, 'keys'), join(tmpDir, 'keys'), { optional: true });
|
||||
copyBuildArtifacts(join(serverDir, '.env'), join(tmpDir, '.env'), { optional: true });
|
||||
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, buildDir: string): Promise<void> {
|
||||
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 = '/tmp/ecom-license-build.tar.gz';
|
||||
execSync(`tar -czf "${tmpTar}" -C "${buildDir}" .`, { stdio: 'pipe' });
|
||||
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('/tmp/ecom-license.Dockerfile', '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');
|
||||
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('/tmp/ecom-license.Dockerfile', readFileSync(dockerfileSrc, 'utf8'));
|
||||
writeFileSync(dockerfileTmp, readFileSync(dockerfileSrc, 'utf8'));
|
||||
}
|
||||
|
||||
await uploadFile(conn, tmpTar, `${serviceDir}/build.tar.gz`);
|
||||
await uploadFile(conn, '/tmp/ecom-license.Dockerfile', `${serviceDir}/Dockerfile`);
|
||||
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);
|
||||
await remoteBuildImage(conn, 'license', serviceDir, env);
|
||||
}
|
||||
|
||||
+118
-32
@@ -1,92 +1,178 @@
|
||||
import { writeFileSync } from 'fs';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { resolveSpringProfile } from './config.js';
|
||||
import { getDockerResourceNames, resolveBackendPort, resolveSpringProfile } from './config.js';
|
||||
import { getLocalTempPath } from './platform.js';
|
||||
import { execRemote, ensureRemoteDir, uploadFile } from './ssh.js';
|
||||
import { printSuccess } from './ui/render.js';
|
||||
import type { Service, ServiceEnvConfig } from './types.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from './types.js';
|
||||
|
||||
export function generateComposeFile(service: Service, cfg: ServiceEnvConfig): string {
|
||||
const tag = `ecom-${service}:latest`;
|
||||
/** 远程 compose 命令前缀(固定项目名,避免同目录多环境冲突) */
|
||||
function composeCmd(cfg: ServiceEnvConfig, env: Environment, service: Service): string {
|
||||
const { composeProject } = getDockerResourceNames(service, env);
|
||||
return `cd "${cfg.server.deployPath}" && docker compose -p ${composeProject}`;
|
||||
}
|
||||
|
||||
/** 桥接模式端口:宿主机与容器内保持一致,后端按环境 profile 解析 */
|
||||
function resolveBridgePorts(service: Service, cfg: ServiceEnvConfig, env: Environment): { hostPort: number; containerPort: number } {
|
||||
if (service === 'backend') {
|
||||
const port = resolveBackendPort(env);
|
||||
return { hostPort: port, containerPort: port };
|
||||
}
|
||||
return { hostPort: cfg.port, containerPort: cfg.port };
|
||||
}
|
||||
|
||||
export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env: Environment): string {
|
||||
const { composeService, containerName, imageTag } = getDockerResourceNames(service, env);
|
||||
const { hostPort, containerPort } = resolveBridgePorts(service, cfg, env);
|
||||
|
||||
let envBlock = '';
|
||||
if (service === 'frontend') {
|
||||
envBlock = ` - NGINX_PORT=${cfg.port}`;
|
||||
envBlock = ` - NGINX_PORT=${containerPort}`;
|
||||
} else if (service === 'backend') {
|
||||
// 端口由 application-{profile}.yml 的 server.port 决定,不在此覆盖 SERVER_PORT
|
||||
envBlock = [
|
||||
` - SERVER_PORT=${cfg.port}`,
|
||||
` - SPRING_PROFILES_ACTIVE=${resolveSpringProfile(cfg.springProfile)}`,
|
||||
cfg.dbUrl ? ` - DB_URL=${cfg.dbUrl}` : '',
|
||||
cfg.redisUrl ? ` - REDIS_URL=${cfg.redisUrl}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
} else if (service === 'license') {
|
||||
envBlock = [
|
||||
` - NODE_ENV=${cfg.nodeEnv || 'production'}`,
|
||||
` - PORT=${cfg.port}`,
|
||||
` - NODE_ENV=${cfg.nodeEnv || 'prod'}`,
|
||||
` - PORT=${containerPort}`,
|
||||
cfg.licenseDbUrl ? ` - DB_URL=${cfg.licenseDbUrl}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
return `services:
|
||||
${service}:
|
||||
image: ${tag}
|
||||
container_name: ecom-${service}
|
||||
network_mode: host
|
||||
${composeService}:
|
||||
image: ${imageTag}
|
||||
container_name: ${containerName}
|
||||
pull_policy: never
|
||||
ports:
|
||||
- "${hostPort}:${containerPort}"
|
||||
environment:
|
||||
${envBlock}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- default
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
networks:
|
||||
default:
|
||||
driver: bridge
|
||||
`;
|
||||
}
|
||||
|
||||
export async function remoteBuildImage(conn: Client, service: Service, serviceDir: string): Promise<void> {
|
||||
const tag = `ecom-${service}:latest`;
|
||||
const { code, stdout, stderr } = await execRemote(conn, `cd "${serviceDir}" && docker build -t ${tag} . 2>&1`);
|
||||
export async function remoteBuildImage(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
serviceDir: string,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { imageTag } = getDockerResourceNames(service, env);
|
||||
const { code, stdout, stderr } = await execRemote(
|
||||
conn,
|
||||
`cd "${serviceDir}" && docker build -t ${imageTag} . 2>&1`,
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${service} 镜像构建失败:\n${stdout || stderr}`);
|
||||
}
|
||||
printSuccess(`${service} 镜像构建完成`);
|
||||
printSuccess(`${service} 镜像构建完成 (${imageTag})`);
|
||||
}
|
||||
|
||||
export async function uploadComposeFile(conn: Client, service: Service, cfg: ServiceEnvConfig): Promise<void> {
|
||||
export async function uploadComposeFile(
|
||||
conn: Client,
|
||||
service: Service,
|
||||
cfg: ServiceEnvConfig,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const deployPath = cfg.server.deployPath;
|
||||
const tmpCompose = `/tmp/ecom-${service}-docker-compose.yml`;
|
||||
writeFileSync(tmpCompose, generateComposeFile(service, cfg), 'utf8');
|
||||
const tmpCompose = getLocalTempPath(`ecom-${service}-${env}-docker-compose.yml`);
|
||||
writeFileSync(tmpCompose, generateComposeFile(service, cfg, env), 'utf8');
|
||||
await ensureRemoteDir(conn, deployPath);
|
||||
await uploadFile(conn, tmpCompose, `${deployPath}/docker-compose.yml`);
|
||||
}
|
||||
|
||||
export async function composeUp(conn: Client, cfg: ServiceEnvConfig, service: Service): Promise<void> {
|
||||
const { code, stdout, stderr } = await execRemote(conn, `cd "${cfg.server.deployPath}" && docker compose up -d ${service} 2>&1`);
|
||||
/** 首次启动(不强制重建) */
|
||||
export async function composeUp(conn: Client, cfg: ServiceEnvConfig, service: Service, env: Environment): Promise<void> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
const { code, stdout, stderr } = await execRemote(
|
||||
conn,
|
||||
`${composeCmd(cfg, env, service)} up -d ${composeService} 2>&1`,
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${service} 启动失败:\n${stdout || stderr}`);
|
||||
}
|
||||
printSuccess(`${service} 已启动`);
|
||||
printSuccess(`${composeService} 已启动`);
|
||||
}
|
||||
|
||||
export async function composeDown(conn: Client, cfg: ServiceEnvConfig, service: Service): Promise<void> {
|
||||
await execRemote(conn, `cd "${cfg.server.deployPath}" && docker compose down ${service}`);
|
||||
printSuccess(`${service} 已停止`);
|
||||
/** 部署更新:强制用新镜像重建容器 */
|
||||
export async function composeDeploy(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
const { code, stdout, stderr } = await execRemote(
|
||||
conn,
|
||||
`${composeCmd(cfg, env, service)} up -d --force-recreate --remove-orphans ${composeService} 2>&1`,
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${service} 更新启动失败:\n${stdout || stderr}`);
|
||||
}
|
||||
printSuccess(`${composeService} 已更新并重启`);
|
||||
}
|
||||
|
||||
export async function composeRestart(conn: Client, cfg: ServiceEnvConfig, service: Service): Promise<void> {
|
||||
const { code, stdout, stderr } = await execRemote(conn, `cd "${cfg.server.deployPath}" && docker compose restart ${service} 2>&1`);
|
||||
export async function composeDown(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
await execRemote(conn, `${composeCmd(cfg, env, service)} down ${composeService}`);
|
||||
printSuccess(`${composeService} 已停止`);
|
||||
}
|
||||
|
||||
export async function composeRestart(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
): Promise<void> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
const { code, stdout, stderr } = await execRemote(
|
||||
conn,
|
||||
`${composeCmd(cfg, env, service)} restart ${composeService} 2>&1`,
|
||||
);
|
||||
if (code !== 0) {
|
||||
throw new Error(`${service} 重启失败:\n${stdout || stderr}`);
|
||||
}
|
||||
printSuccess(`${service} 已重启`);
|
||||
printSuccess(`${composeService} 已重启`);
|
||||
}
|
||||
|
||||
export async function composeLogs(conn: Client, cfg: ServiceEnvConfig, service: Service, tail = 50): Promise<string> {
|
||||
const { stdout } = await execRemote(conn, `cd "${cfg.server.deployPath}" && docker compose logs --tail=${tail} ${service}`);
|
||||
export async function composeLogs(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
service: Service,
|
||||
env: Environment,
|
||||
tail = 50,
|
||||
): Promise<string> {
|
||||
const { composeService } = getDockerResourceNames(service, env);
|
||||
const { stdout } = await execRemote(
|
||||
conn,
|
||||
`${composeCmd(cfg, env, service)} logs --tail=${tail} ${composeService}`,
|
||||
);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
export async function composeStatus(conn: Client, cfg: ServiceEnvConfig): Promise<string> {
|
||||
const { stdout } = await execRemote(conn, `cd "${cfg.server.deployPath}" && docker compose ps`);
|
||||
export async function composeStatus(conn: Client, cfg: ServiceEnvConfig, service: Service, env: Environment): Promise<string> {
|
||||
const { stdout } = await execRemote(conn, `${composeCmd(cfg, env, service)} ps`);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ async function selectEnv(): Promise<Environment> {
|
||||
const config = await loadConfig();
|
||||
const env = await select({
|
||||
message: '选择环境',
|
||||
choices: (['test', 'pre', 'production'] as Environment[]).map((e) => ({
|
||||
choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({
|
||||
name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`,
|
||||
value: e,
|
||||
})),
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { execSync } from 'child_process';
|
||||
import { cpSync, existsSync, readdirSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
|
||||
/** 本地临时目录(跨平台,替代 /tmp) */
|
||||
export function getLocalTempPath(name: string): string {
|
||||
return join(tmpdir(), name);
|
||||
}
|
||||
|
||||
/** 解析 Maven 命令:Windows 用 mvnw.cmd,Unix 用 mvnw */
|
||||
export function resolveMavenCommand(projectDir: string): string {
|
||||
if (process.platform === 'win32') {
|
||||
const mvnwCmd = join(projectDir, 'mvnw.cmd');
|
||||
if (existsSync(mvnwCmd)) return `"${mvnwCmd}"`;
|
||||
} else {
|
||||
const mvnw = join(projectDir, 'mvnw');
|
||||
if (existsSync(mvnw)) return `"${mvnw}"`;
|
||||
}
|
||||
return 'mvn';
|
||||
}
|
||||
|
||||
/** 在 target 目录查找主 JAR(排除 *-original.jar) */
|
||||
export function findMainJar(targetDir: string): string {
|
||||
const jars = readdirSync(targetDir).filter(
|
||||
(f) => f.endsWith('.jar') && !f.endsWith('-original.jar'),
|
||||
);
|
||||
if (jars.length === 0) throw new Error(`未找到 JAR 文件: ${targetDir}`);
|
||||
return join(targetDir, jars[0]);
|
||||
}
|
||||
|
||||
/** 将目录打包为 tar.gz(Windows 10+ / Linux / macOS 均内置 tar) */
|
||||
export function createTarGz(sourceDir: string, destPath: string): void {
|
||||
try {
|
||||
execSync(`tar -czf "${destPath}" -C "${sourceDir}" .`, { stdio: 'pipe' });
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`打包失败 (${sourceDir}): ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 递归复制目录/文件到临时构建目录 */
|
||||
export function copyBuildArtifacts(src: string, dest: string, opts?: { optional?: boolean }): void {
|
||||
if (!existsSync(src)) {
|
||||
if (opts?.optional) return;
|
||||
throw new Error(`源路径不存在: ${src}`);
|
||||
}
|
||||
cpSync(src, dest, { recursive: true });
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export type Environment = 'test' | 'pre' | 'production';
|
||||
export type Environment = 'test' | 'pre' | 'prod';
|
||||
export type Service = 'frontend' | 'backend' | 'license';
|
||||
|
||||
export interface ServerConfig {
|
||||
@@ -36,5 +36,5 @@ export const SERVICE_LABELS: Record<Service, string> = {
|
||||
export const ENV_LABELS: Record<Environment, string> = {
|
||||
test: '测试环境',
|
||||
pre: '预发布环境',
|
||||
production: '生产环境',
|
||||
prod: '生产环境',
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user