#!/usr/bin/env bash # 构建 api / player / admin 生产镜像并导出为 tar # 用法: # ./docs/docker/build-and-export-images.sh # ./build-and-export-images.sh --use-cache # ./build-and-export-images.sh --export-only set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" cd "$ROOT" COMPOSE_FILE="docker-compose.prod.yml" ENV_FILE=".env.docker" OUTPUT="thebet365-images.tar" SERVICES=(api player admin) NO_CACHE=1 EXPORT_ONLY=0 usage() { cat <<'EOF' 用法: docs/docker/build-and-export-images.sh [选项] 选项: --use-cache 构建时使用 Docker 缓存(默认 --no-cache) --export-only 跳过构建,仅导出已有 latest 镜像 --output PATH 导出文件路径(默认项目根目录 thebet365-images.tar) -h, --help 显示帮助 EOF } while [[ $# -gt 0 ]]; do case "$1" in --use-cache) NO_CACHE=0; shift ;; --export-only) EXPORT_ONLY=1; shift ;; --output) OUTPUT="${2:?缺少 --output 参数值}" shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "未知参数: $1" >&2; usage; exit 1 ;; esac done if [[ ! -f "$COMPOSE_FILE" ]]; then echo "错误: 未找到 $COMPOSE_FILE(目录: $ROOT)" >&2 exit 1 fi if [[ ! -f "$ENV_FILE" ]]; then if [[ -f ".env.docker.example" ]]; then echo "警告: 未找到 $ENV_FILE,将使用 .env.docker.example(生产部署请复制为 .env.docker 并修改密钥)" ENV_FILE=".env.docker.example" else echo "错误: 未找到 $ENV_FILE 或 .env.docker.example" >&2 exit 1 fi fi if [[ "$EXPORT_ONLY" -eq 0 ]]; then echo "==> 构建镜像: ${SERVICES[*]}" BUILD_ARGS=(compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" build) if [[ "$NO_CACHE" -eq 1 ]]; then BUILD_ARGS+=(--no-cache) fi BUILD_ARGS+=("${SERVICES[@]}") docker "${BUILD_ARGS[@]}" fi OUTPUT_PATH="$OUTPUT" if [[ "$OUTPUT" != /* ]] && [[ "$OUTPUT" != [A-Za-z]:* ]]; then OUTPUT_PATH="$ROOT/$OUTPUT" fi echo "==> 导出镜像 -> $OUTPUT_PATH" docker save \ thebet365-api:latest \ thebet365-player:latest \ thebet365-admin:latest \ -o "$OUTPUT_PATH" if command -v du >/dev/null 2>&1; then SIZE="$(du -h "$OUTPUT_PATH" | awk '{print $1}')" echo "完成: $OUTPUT_PATH ($SIZE)" else echo "完成: $OUTPUT_PATH" fi cat <<'EOF' 服务器首次部署: ./scripts/deploy-first.sh --images thebet365-images.tar 服务器后续更新: ./scripts/deploy-update.sh --images thebet365-images.tar EOF