bw-mini-app-server/BUILD.md

195 lines
3.7 KiB
Markdown
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.

# 构建和部署指南
本项目提供了多个构建脚本,可以自动识别 git commit hash 作为 Docker 镜像标签。
## 📁 脚本文件
- **`build.sh`** - 完整的构建脚本,支持多种选项
- **`docker-build.sh`** - 简化的快速构建脚本
- **`deploy.sh`** - 部署脚本,可选择是否重新构建
## 🚀 快速开始
### 1. 快速构建
```bash
# 最简单的构建方式
./docker-build.sh
```
### 2. 完整构建
```bash
# 生产环境构建
./build.sh
# 开发环境构建
./build.sh --env=development
# 构建并推送到仓库
./build.sh --push
```
### 3. 使用 npm scripts
```bash
# Docker 构建
npm run build:docker
# 开发环境构建
npm run build:docker:dev
# 构建并推送
npm run build:docker:push
# 生产环境构建并推送
npm run build:prod
```
## 🏷️ 标签策略
构建脚本会自动生成以下标签:
### 有 Git Tag 的情况
- 主标签:`bw-mini-app-server:v1.0.0` (使用 git tag)
- 额外标签:
- `bw-mini-app-server:e30d7cc` (commit hash)
- `bw-mini-app-server:latest`
### 无 Git Tag 的情况
- 主标签:`bw-mini-app-server:e30d7cc` (commit hash)
- 额外标签:
- `bw-mini-app-server:latest` (main/master 分支)
- `bw-mini-app-server:feature-latest` (其他分支)
## 📋 构建信息
每次构建后会生成 `deployment-info.json` 文件,包含:
```json
{
"image": "bw-mini-app-server:e30d7cc",
"git": {
"commit": "e30d7cc",
"branch": "main",
"tag": ""
},
"build": {
"time": "2024-01-15_14:30:25",
"environment": "production"
},
"tags": ["e30d7cc", "latest"]
}
```
## 🔧 脚本选项
### build.sh 选项
```bash
./build.sh [选项]
选项:
--push 构建后推送镜像到仓库
--env=ENV 指定环境 (production|development默认: production)
-h, --help 显示此帮助信息
```
### deploy.sh 选项
```bash
./deploy.sh [选项]
选项:
--env=ENV 指定环境 (production|development默认: production)
--build 重新构建镜像
-h, --help 显示此帮助信息
```
## 🐳 Docker Compose
### 开发环境
```bash
# 启动开发环境
npm run docker:up
# 或
docker-compose up -d
# 查看日志
npm run docker:logs
# 或
docker-compose logs -f
```
### 生产环境
```bash
# 启动生产环境
npm run docker:up:prod
# 或
docker-compose --profile production up -d
```
## 🛠️ 环境变量
在 Dockerfile 中设置了以下构建时环境变量:
- `GIT_COMMIT` - Git commit hash
- `GIT_BRANCH` - Git 分支名
- `BUILD_TIME` - 构建时间
这些变量可以在应用中访问:
```javascript
console.log('Git Commit:', process.env.GIT_COMMIT);
console.log('Git Branch:', process.env.GIT_BRANCH);
console.log('Build Time:', process.env.BUILD_TIME);
```
## 🔍 故障排除
### 常见问题
1. **权限错误**
```bash
chmod +x build.sh docker-build.sh deploy.sh
```
2. **Git 仓库检查失败**
确保在 git 仓库目录中运行脚本
3. **Docker 构建失败**
检查 Docker 是否正在运行,以及 Dockerfile 语法是否正确
### 检查构建结果
```bash
# 查看构建的镜像
docker images | grep bw-mini-app-server
# 运行测试
docker run -p 3000:3000 bw-mini-app-server:latest
# 检查容器日志
docker logs <容器ID>
```
## 💡 最佳实践
1. **提交代码后构建**:确保在构建前提交所有更改
2. **使用标签发布**:重要版本使用 git tag 标记
3. **环境隔离**:开发和生产环境使用不同的构建配置
4. **定期清理**:清理不需要的 Docker 镜像以节省空间
```bash
# 清理未使用的镜像
docker image prune -f
# 清理所有未使用的资源
docker system prune -f
```