Files
ai_trading_api/create/create_src_dockerfile.py
2025-12-26 17:20:50 +08:00

96 lines
3.0 KiB
Python
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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
create_src_dockerfile.py - 更新Dockerfile内容
"""
import os
import sys
def update_dockerfile(table_name):
"""更新指定服务目录下的Dockerfile内容"""
# 获取项目根目录
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
services_dir = os.path.join(project_root, 'services')
# 服务目录路径
service_dir = os.path.join(services_dir, table_name)
dockerfile_path = os.path.join(service_dir, 'src', 'Dockerfile')
print(f"🚀 开始更新Dockerfile: {dockerfile_path}")
# Dockerfile内容
dockerfile_content = """# ==================== 第一阶段构建Go程序构建阶段====================
# 使用官方Go镜像作为构建基础选择与项目匹配的Go版本示例用1.25.0,可根据实际调整)
FROM golang:1.25.0-alpine3.22 AS builder
# 设置工作目录(容器内的目录,规范文件位置)
WORKDIR /app
# 复制go.mod和go.sum先复制依赖文件利用Docker缓存机制避免每次代码变动都重新下载依赖
COPY go.mod go.sum ./
# 下载项目依赖仅当go.mod/go.sum变动时才会重新执行
RUN go mod download
# 复制整个项目代码到工作目录
COPY . .
# 构建Go程序
# - CGO_ENABLED=0禁用CGO生成静态链接的二进制文件避免依赖系统库保证镜像兼容性
# - -o app指定输出二进制文件名为app
# - ./main.go指定入口文件
RUN CGO_ENABLED=0 GOOS=linux go build -o app ./main.go
# ==================== 第二阶段:运行程序(运行阶段)====================
# 使用轻量级的scratch大幅减小最终镜像体积
FROM scratch
# 设置工作目录
WORKDIR /app
# 从构建阶段复制编译好的二进制文件到当前镜像(仅复制最终产物,减小体积)
COPY --from=builder /app/app ./
# 暴露程序运行端口(与代码中一致)
EXPOSE 80
# 容器启动时执行的命令:运行二进制文件
CMD ["./app"]
"""
try:
# 检查文件是否存在
if not os.path.exists(dockerfile_path):
print(f"❌ Dockerfile不存在: {dockerfile_path}")
return False
# 清空文件内容并写入新内容
with open(dockerfile_path, 'w', encoding='utf-8') as f:
f.write(dockerfile_content)
print(f"✅ 成功更新Dockerfile: {dockerfile_path}")
print(f"📋 Dockerfile内容已完全替换")
return True
except Exception as e:
print(f"❌ 更新Dockerfile时出错: {e}")
return False
if __name__ == "__main__":
# 从环境变量获取表名
table_name = os.environ.get('TABLE_NAME')
if not table_name:
print("❌ 错误: 未设置 TABLE_NAME 环境变量")
sys.exit(1)
print(f"📋 接收到的表名: {table_name}")
success = update_dockerfile(table_name)
if success:
sys.exit(0)
else:
sys.exit(1)