|
#!/bin/bash |
|
|
|
|
|
|
|
set -e |
|
|
|
echo "🚀 部署聊天应用到生产环境..." |
|
echo |
|
|
|
|
|
if [ "$EUID" -ne 0 ]; then |
|
echo "⚠️ 建议使用sudo运行此脚本以确保权限充足" |
|
fi |
|
|
|
|
|
if ! command -v docker &> /dev/null; then |
|
echo "❌ 错误: Docker未安装" |
|
echo "正在安装Docker..." |
|
curl -fsSL https://get.docker.com -o get-docker.sh |
|
sh get-docker.sh |
|
rm get-docker.sh |
|
systemctl enable docker |
|
systemctl start docker |
|
echo "✅ Docker安装完成" |
|
fi |
|
|
|
|
|
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then |
|
echo "❌ 错误: Docker Compose未安装" |
|
echo "正在安装Docker Compose..." |
|
curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose |
|
chmod +x /usr/local/bin/docker-compose |
|
echo "✅ Docker Compose安装完成" |
|
fi |
|
|
|
|
|
if ! docker info &> /dev/null; then |
|
echo "🔄 启动Docker服务..." |
|
systemctl start docker |
|
fi |
|
|
|
echo "✅ Docker环境准备完成" |
|
echo |
|
|
|
|
|
chmod +x start.sh stop.sh start-dev.sh |
|
|
|
|
|
echo "⚙️ 配置生产环境..." |
|
|
|
|
|
JWT_SECRET=$(openssl rand -base64 32) |
|
|
|
|
|
cat > .env.production << EOF |
|
# 生产环境配置 |
|
NODE_ENV=production |
|
MONGODB_URI=mongodb://admin:$(openssl rand -base64 12)@mongo:27017/chatapp?authSource=admin |
|
JWT_SECRET=${JWT_SECRET} |
|
PORT=5000 |
|
CLIENT_URL=http://localhost:3000 |
|
EOF |
|
|
|
echo "✅ 生产环境配置完成" |
|
echo |
|
|
|
|
|
echo "🛑 停止现有服务..." |
|
if command -v docker-compose &> /dev/null; then |
|
docker-compose down 2>/dev/null || true |
|
else |
|
docker compose down 2>/dev/null || true |
|
fi |
|
|
|
|
|
echo "🧹 清理旧镜像..." |
|
docker system prune -f |
|
|
|
|
|
echo "📦 构建并启动生产服务..." |
|
if command -v docker-compose &> /dev/null; then |
|
docker-compose up --build -d |
|
else |
|
docker compose up --build -d |
|
fi |
|
|
|
|
|
echo "⏳ 等待服务启动..." |
|
sleep 30 |
|
|
|
|
|
echo "🔍 检查服务状态..." |
|
if command -v docker-compose &> /dev/null; then |
|
docker-compose ps |
|
else |
|
docker compose ps |
|
fi |
|
|
|
|
|
echo "🧪 测试服务..." |
|
if curl -f http://localhost:5000/api/health > /dev/null 2>&1; then |
|
echo "✅ 后端服务正常" |
|
else |
|
echo "❌ 后端服务异常" |
|
fi |
|
|
|
if curl -f http://localhost:3000 > /dev/null 2>&1; then |
|
echo "✅ 前端服务正常" |
|
else |
|
echo "❌ 前端服务异常" |
|
fi |
|
|
|
echo |
|
echo "🎉 部署完成!" |
|
echo |
|
echo "🌐 前端地址: http://localhost:3000" |
|
echo "🔧 后端API: http://localhost:5000" |
|
echo "📊 MongoDB: localhost:27017" |
|
echo |
|
echo "📋 常用命令:" |
|
echo " - 查看日志: docker-compose logs -f" |
|
echo " - 重启服务: docker-compose restart" |
|
echo " - 停止服务: ./stop.sh" |
|
echo " - 更新应用: ./deploy.sh" |
|
echo |
|
echo "🔒 安全提醒:" |
|
echo " - 请修改默认密码" |
|
echo " - 配置防火墙规则" |
|
echo " - 启用HTTPS (推荐使用nginx反向代理)" |
|
echo " - 定期备份数据库" |
|
|