mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat(部署): 优化部署目录
This commit is contained in:
@@ -16,6 +16,14 @@
|
||||
├── docker-compose.yml
|
||||
├── Dockerfile
|
||||
└── app/
|
||||
├── app.jar # 每次部署更新
|
||||
├── application-{profile}.yml # 环境配置(与 jar 同级,首次从仓库初始化)
|
||||
├── config/ # license、渠道配置等
|
||||
│ ├── channel-pdd.yml
|
||||
│ ├── license.key
|
||||
│ └── revoked.jti
|
||||
├── uploads/ # 本地上传文件(持久化,部署不覆盖)
|
||||
└── static/ # 静态资源(含 extension-features,部署合并同步)
|
||||
```
|
||||
|
||||
**前端(静态,用目录名区分环境)**:
|
||||
@@ -28,6 +36,10 @@
|
||||
|
||||
```
|
||||
/opt/ecom-dmb/backend/test/app/app.jar
|
||||
/opt/ecom-dmb/backend/test/app/application-test.yml
|
||||
/opt/ecom-dmb/backend/test/app/config/license.key
|
||||
/opt/ecom-dmb/backend/test/app/uploads/
|
||||
/opt/ecom-dmb/backend/test/app/static/
|
||||
/opt/ecom-dmb-test/index/ # 前端站点根
|
||||
/opt/ecom-dmb/license/test/app/
|
||||
```
|
||||
@@ -39,7 +51,7 @@ Docker 资源名同样带环境后缀:`ecom-backend-test` / `ecom-backend-prod
|
||||
```
|
||||
artifacts/
|
||||
├── frontend/ # 前端 dist 静态文件
|
||||
├── backend/ # app.jar
|
||||
├── backend/ # app.jar + static/
|
||||
└── license/ # dist、package.json、node_modules 等
|
||||
```
|
||||
|
||||
@@ -97,9 +109,16 @@ pnpm install --prod --frozen-lockfile
|
||||
**后端**(根目录 `/opt`,test 环境):
|
||||
|
||||
```bash
|
||||
# 推荐用 TUI「上传产物并重启」;手动时至少更新 jar,static 可选
|
||||
scp artifacts/backend/app.jar user@192.168.3.101:/opt/ecom-dmb/backend/test/app/app.jar
|
||||
# static(扩展功能脚本等,合并到宿主机 static/)
|
||||
tar -czf static.tar.gz -C artifacts/backend/static .
|
||||
scp static.tar.gz user@host:/opt/ecom-dmb/backend/test/app/
|
||||
ssh user@host 'mkdir -p /opt/ecom-dmb/backend/test/app/static && tar -xzf /opt/ecom-dmb/backend/test/app/static.tar.gz -C /opt/ecom-dmb/backend/test/app/static && rm -f /opt/ecom-dmb/backend/test/app/static.tar.gz'
|
||||
```
|
||||
|
||||
首次部署后请在服务器编辑 `app/application-{profile}.yml` 与 `app/config/license.key`;`uploads/` 与上述配置文件不会被后续部署覆盖。
|
||||
|
||||
**许可证**:
|
||||
|
||||
```bash
|
||||
@@ -121,10 +140,10 @@ Nginx 站点根目录一般为 `/opt/ecom-dmb-{env}/index`(如 test → `/opt/
|
||||
### 3. 重启容器
|
||||
|
||||
```bash
|
||||
# 后端 test 环境
|
||||
# 后端 test 环境(up -d 会应用 compose 卷变更;仅换 jar 时 restart 亦可)
|
||||
ssh user@192.168.3.101
|
||||
cd /opt/ecom-dmb/backend/test
|
||||
docker compose -p ecom-backend-test restart ecom-backend-test
|
||||
docker compose -p ecom-backend-test up -d ecom-backend-test
|
||||
```
|
||||
|
||||
各环境容器名:`ecom-backend-test` / `ecom-backend-pre` / `ecom-backend-prod`
|
||||
|
||||
@@ -2,7 +2,7 @@ import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { getArtifactDir, getArtifactsRoot } from './config.js';
|
||||
import { getArtifactDir, getArtifactsRoot, getBackendDir } from './config.js';
|
||||
import { createTarGz, getLocalTempPath } from './platform.js';
|
||||
import { ensureRemoteDir, execRemote, uploadFile } from './ssh.js';
|
||||
import { printInfo } from './ui/render.js';
|
||||
@@ -25,10 +25,14 @@ export function clearArtifactDir(service: Service): void {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
/** 同步后端 JAR 到 artifacts/backend/app.jar */
|
||||
/** 同步后端 JAR 与 static 到 artifacts/backend/ */
|
||||
export function syncBackendArtifact(jarPath: string): string {
|
||||
clearArtifactDir('backend');
|
||||
cpSync(jarPath, join(getArtifactDir('backend'), 'app.jar'));
|
||||
const staticSrc = join(getBackendDir(), 'src/main/resources/static');
|
||||
if (existsSync(staticSrc)) {
|
||||
cpSync(staticSrc, join(getArtifactDir('backend'), 'static'), { recursive: true });
|
||||
}
|
||||
return getArtifactDir('backend');
|
||||
}
|
||||
|
||||
@@ -87,3 +91,25 @@ export async function uploadArtifactDirectory(
|
||||
);
|
||||
if (code !== 0) throw new Error(`远程解压失败: ${stderr}`);
|
||||
}
|
||||
|
||||
/** 将本地目录打包解压到远程目录(合并,不清空目标) */
|
||||
export async function uploadDirectoryMerge(
|
||||
conn: Client,
|
||||
localDir: string,
|
||||
remoteDir: string,
|
||||
): Promise<void> {
|
||||
if (!existsSync(localDir)) return;
|
||||
await ensureRemoteDir(conn, remoteDir);
|
||||
const parentDir = remoteDir.replace(/\/+$/, '');
|
||||
const tmpTar = getLocalTempPath(`ecom-merge-${Date.now()}.tar.gz`);
|
||||
const remoteTar = `${parentDir}/merge-upload.tar.gz`;
|
||||
|
||||
createTarGz(localDir, tmpTar);
|
||||
await uploadFile(conn, tmpTar, remoteTar);
|
||||
|
||||
const { code, stderr } = await execRemote(
|
||||
conn,
|
||||
`mkdir -p "${remoteDir}" && tar -xzf "${remoteTar}" -C "${remoteDir}" && rm -f "${remoteTar}"`,
|
||||
);
|
||||
if (code !== 0) throw new Error(`远程合并解压失败: ${stderr}`);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,15 @@ import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Client } from 'ssh2';
|
||||
import { syncBackendArtifact } from '../artifacts.js';
|
||||
import { getArtifactDir, getBackendDir, getRemoteAppDir } from '../config.js';
|
||||
import { syncBackendArtifact, uploadDirectoryMerge } from '../artifacts.js';
|
||||
import {
|
||||
getArtifactDir,
|
||||
getBackendDir,
|
||||
getRemoteAppDir,
|
||||
resolveSpringProfile,
|
||||
} from '../config.js';
|
||||
import { findMainJar, resolveMavenCommand } from '../platform.js';
|
||||
import { ensureRemoteDir, uploadFile } from '../ssh.js';
|
||||
import { ensureRemoteDir, execRemote, uploadFile } from '../ssh.js';
|
||||
import { printInfo, printSuccess } from '../ui/render.js';
|
||||
import type { Environment, Service, ServiceEnvConfig } from '../types.js';
|
||||
|
||||
@@ -31,11 +36,52 @@ export async function build(_cfg: ServiceEnvConfig): Promise<string> {
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
/** 上传 artifacts/backend 到远程挂载目录 */
|
||||
/** 远程尚无文件时初始化环境 yml(app 根目录)与 config/ 下的 license 相关文件 */
|
||||
async function seedRemoteConfigIfMissing(
|
||||
conn: Client,
|
||||
cfg: ServiceEnvConfig,
|
||||
remoteAppDir: string,
|
||||
): Promise<void> {
|
||||
const profile = resolveSpringProfile(cfg.springProfile);
|
||||
const backendDir = getBackendDir();
|
||||
const envYml = `application-${profile}.yml`;
|
||||
const seeds: { local: string; remote: string }[] = [
|
||||
{
|
||||
local: join(backendDir, 'src/main/resources', envYml),
|
||||
remote: `${remoteAppDir}/${envYml}`,
|
||||
},
|
||||
{
|
||||
local: join(backendDir, 'src/main/resources/config/channel-pdd.yml'),
|
||||
remote: `${remoteAppDir}/config/channel-pdd.yml`,
|
||||
},
|
||||
];
|
||||
|
||||
await ensureRemoteDir(conn, `${remoteAppDir}/config`);
|
||||
for (const { local, remote } of seeds) {
|
||||
if (!existsSync(local)) continue;
|
||||
const { code } = await execRemote(conn, `test -f "${remote}"`);
|
||||
if (code === 0) continue;
|
||||
await uploadFile(conn, local, remote);
|
||||
printInfo(`已初始化配置(仅首次): ${remote}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传 artifacts/backend 到远程 app/(jar + static;config/uploads 保留宿主机数据) */
|
||||
export async function deploy(conn: Client, cfg: ServiceEnvConfig, _buildDir: string, env: Environment): Promise<void> {
|
||||
const artifactDir = getArtifactDir('backend');
|
||||
const remoteAppDir = getRemoteAppDir(cfg, 'backend', env);
|
||||
|
||||
await ensureRemoteDir(conn, remoteAppDir);
|
||||
await ensureRemoteDir(conn, `${remoteAppDir}/uploads`);
|
||||
await seedRemoteConfigIfMissing(conn, cfg, remoteAppDir);
|
||||
|
||||
await uploadFile(conn, join(artifactDir, 'app.jar'), `${remoteAppDir}/app.jar`);
|
||||
|
||||
const localStatic = join(artifactDir, 'static');
|
||||
if (existsSync(localStatic)) {
|
||||
printInfo('同步 static/ 到远程(合并,不删除 uploads/ 与宿主机配置)...');
|
||||
await uploadDirectoryMerge(conn, localStatic, `${remoteAppDir}/static`);
|
||||
}
|
||||
|
||||
printSuccess(`后端产物已上传到 ${remoteAppDir}`);
|
||||
}
|
||||
|
||||
@@ -32,6 +32,16 @@ function resolveBridgePorts(service: Service, cfg: ServiceEnvConfig, env: Enviro
|
||||
return { hostPort: cfg.port, containerPort: cfg.port };
|
||||
}
|
||||
|
||||
function backendComposeVolumes(profile: string): string {
|
||||
return [
|
||||
' - ./app/app.jar:/app/app.jar:ro',
|
||||
` - ./app/application-${profile}.yml:/app/application-${profile}.yml:ro`,
|
||||
' - ./app/config:/app/config:ro',
|
||||
' - ./app/uploads:/app/uploads:rw',
|
||||
' - ./app/static:/app/static:ro',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env: Environment): string {
|
||||
const { composeService, containerName, imageTag } = getDockerResourceNames(service, env);
|
||||
const { hostPort, containerPort } = resolveBridgePorts(service, cfg, env);
|
||||
@@ -53,6 +63,10 @@ export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env
|
||||
].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
const volumeBlock = service === 'backend'
|
||||
? backendComposeVolumes(resolveSpringProfile(cfg.springProfile))
|
||||
: ' - ./app:/app:ro';
|
||||
|
||||
return `services:
|
||||
${composeService}:
|
||||
image: ${imageTag}
|
||||
@@ -61,7 +75,7 @@ export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env
|
||||
ports:
|
||||
- "${hostPort}:${containerPort}"
|
||||
volumes:
|
||||
- ./app:/app:ro
|
||||
${volumeBlock}
|
||||
environment:
|
||||
${envBlock}
|
||||
restart: unless-stopped
|
||||
@@ -165,12 +179,10 @@ export async function composeRestartAfterUpload(
|
||||
const running = psOut.trim().length > 0;
|
||||
|
||||
if (running) {
|
||||
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(`${composeService} 已重启`);
|
||||
const upCmd = `${composeCmd(cfg, env, service)} up -d ${composeService} 2>&1`;
|
||||
const { code, stdout, stderr } = await execRemote(conn, upCmd);
|
||||
if (code !== 0) throw new Error(`${service} 应用 compose 失败:\n${stdout || stderr}`);
|
||||
printSuccess(`${composeService} 已更新并运行`);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,4 +8,5 @@ RUN addgroup -S app && adduser -S app -G app
|
||||
USER app
|
||||
# 实际端口由 Spring profile 决定(test:8101 / pre:8102 / prod:8103)
|
||||
EXPOSE 8101 8102 8103
|
||||
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
|
||||
# 环境 yml 与 app.jar 同级;license 等仍在 ./config/
|
||||
ENTRYPOINT ["java", "-jar", "/app/app.jar", "--spring.config.additional-location=optional:file:./"]
|
||||
|
||||
+2
-1
@@ -15,8 +15,9 @@ public class WebConfig implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addResourceHandlers(@NonNull ResourceHandlerRegistry registry) {
|
||||
// 配置静态资源处理
|
||||
// 部署时可将 static/ 挂载到工作目录,优先于 jar 内 classpath
|
||||
registry.addResourceHandler("/static/**")
|
||||
.addResourceLocations("classpath:/static/");
|
||||
.addResourceLocations("file:./static/", "classpath:/static/");
|
||||
|
||||
// 配置上传文件访问 - 使用绝对路径
|
||||
registry.addResourceHandler("/uploads/**")
|
||||
|
||||
+15
-5
@@ -3,6 +3,7 @@ package top.xyquan.ecomdmbbackend.modules.open.api.extension.features.service.im
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StreamUtils;
|
||||
@@ -20,20 +21,20 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* 从 classpath:static/extension-features/ 读取扩展功能清单与脚本。
|
||||
* 读取扩展功能清单与脚本;优先 ./static/extension-features/(部署挂载),否则 classpath。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ExtensionFeatureServiceImpl implements ExtensionFeatureService {
|
||||
|
||||
private static final String MANIFEST_PATH = "static/extension-features/manifest.json";
|
||||
private static final String FEATURE_DIR = "static/extension-features/";
|
||||
private static final String MANIFEST_REL = "extension-features/manifest.json";
|
||||
private static final String FEATURE_DIR_REL = "extension-features/";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public ExtensionFeatureManifestVO getManifest() {
|
||||
Resource resource = new ClassPathResource(MANIFEST_PATH);
|
||||
Resource resource = resolveFeatureResource(MANIFEST_REL);
|
||||
if (!resource.exists()) {
|
||||
throw new BusinessException("扩展功能清单不存在,请先部署 dist-features 到 static/extension-features/");
|
||||
}
|
||||
@@ -65,7 +66,7 @@ public class ExtensionFeatureServiceImpl implements ExtensionFeatureService {
|
||||
throw new BusinessException("非法脚本路径");
|
||||
}
|
||||
|
||||
Resource resource = new ClassPathResource(FEATURE_DIR + normalized);
|
||||
Resource resource = resolveFeatureResource(FEATURE_DIR_REL + normalized);
|
||||
if (!resource.exists()) {
|
||||
throw new BusinessException("功能脚本文件不存在: " + entry);
|
||||
}
|
||||
@@ -81,4 +82,13 @@ public class ExtensionFeatureServiceImpl implements ExtensionFeatureService {
|
||||
throw new BusinessException("读取功能脚本失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 挂载目录 static/extension-features 优先于 jar 内资源 */
|
||||
private Resource resolveFeatureResource(String relativePath) {
|
||||
FileSystemResource mounted = new FileSystemResource(Paths.get("static", relativePath));
|
||||
if (mounted.exists()) {
|
||||
return mounted;
|
||||
}
|
||||
return new ClassPathResource("static/" + relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ spring:
|
||||
config:
|
||||
import:
|
||||
- optional:classpath:config/channel-pdd.yml
|
||||
- optional:file:./config/channel-pdd.yml
|
||||
jackson:
|
||||
time-zone: Asia/Shanghai
|
||||
mvc:
|
||||
|
||||
Reference in New Issue
Block a user