#!/bin/bash # Docker镜像构建脚本 set -e echo "🐳 Docker镜像构建脚本" echo "====================" echo # 检查Docker是否安装 if ! command -v docker &> /dev/null; then echo "❌ 错误: Docker未安装" echo "请先安装Docker: https://docs.docker.com/engine/install/" exit 1 fi # 检查Docker服务是否运行 if ! docker info &> /dev/null; then echo "❌ 错误: Docker服务未运行" echo "请启动Docker服务: sudo systemctl start docker" exit 1 fi echo "✅ Docker环境检查通过" echo # 设置镜像标签 IMAGE_TAG=${1:-latest} REGISTRY=${2:-""} if [ -n "$REGISTRY" ]; then FULL_TAG="$REGISTRY/chatapp:$IMAGE_TAG" else FULL_TAG="chatapp:$IMAGE_TAG" fi echo "📦 构建配置:" echo " 镜像标签: $FULL_TAG" echo " 构建上下文: $(pwd)" echo # 选择构建方式 echo "请选择构建方式:" echo "1) 多容器构建 (推荐)" echo "2) 单容器构建" echo "3) 仅构建前端" echo "4) 仅构建后端" echo read -p "请输入选择 (1-4): " choice case $choice in 1) echo "🔨 构建多容器版本..." # 构建前端镜像 echo "📦 构建前端镜像..." docker build -t "${FULL_TAG}-frontend" ./client # 构建后端镜像 echo "📦 构建后端镜像..." docker build -t "${FULL_TAG}-backend" ./server echo "✅ 多容器镜像构建完成" echo " 前端镜像: ${FULL_TAG}-frontend" echo " 后端镜像: ${FULL_TAG}-backend" ;; 2) echo "🔨 构建单容器版本..." docker build -t "$FULL_TAG" . echo "✅ 单容器镜像构建完成: $FULL_TAG" ;; 3) echo "🔨 构建前端镜像..." docker build -t "${FULL_TAG}-frontend" ./client echo "✅ 前端镜像构建完成: ${FULL_TAG}-frontend" ;; 4) echo "🔨 构建后端镜像..." docker build -t "${FULL_TAG}-backend" ./server echo "✅ 后端镜像构建完成: ${FULL_TAG}-backend" ;; *) echo "❌ 无效选择" exit 1 ;; esac echo # 显示构建的镜像 echo "📋 构建的镜像:" docker images | grep chatapp echo # 询问是否推送到仓库 if [ -n "$REGISTRY" ]; then read -p "是否推送镜像到仓库? (y/N): " push_choice if [[ $push_choice =~ ^[Yy]$ ]]; then echo "📤 推送镜像到仓库..." case $choice in 1) docker push "${FULL_TAG}-frontend" docker push "${FULL_TAG}-backend" ;; 2) docker push "$FULL_TAG" ;; 3) docker push "${FULL_TAG}-frontend" ;; 4) docker push "${FULL_TAG}-backend" ;; esac echo "✅ 镜像推送完成" fi fi # 询问是否运行测试 read -p "是否运行容器测试? (y/N): " test_choice if [[ $test_choice =~ ^[Yy]$ ]]; then echo "🧪 运行容器测试..." case $choice in 1) echo "启动多容器测试环境..." docker-compose up -d sleep 30 ./test.sh docker-compose down ;; 2) echo "启动单容器测试环境..." docker-compose -f docker-compose.single.yml up -d sleep 30 ./test.sh docker-compose -f docker-compose.single.yml down ;; 3|4) echo "⚠️ 单独的前端或后端镜像需要完整环境才能测试" ;; esac fi echo echo "🎉 构建完成!" echo echo "💡 使用提示:" echo " - 查看镜像: docker images | grep chatapp" echo " - 运行容器: docker run -p 3000:80 $FULL_TAG" echo " - 清理镜像: docker rmi $FULL_TAG" echo echo "📚 更多命令:" echo " - make build # 使用Makefile构建" echo " - make start # 启动应用" echo " - make test # 运行测试"