fix: 自动处理配置文件复制和密钥生成

- 修改docker-entrypoint.sh自动从模板复制config.js和.env文件
- 自动生成JWT_SECRET(64字符)和ENCRYPTION_KEY(32字符)
- 自动配置Redis连接到容器内的redis服务
- 添加sed工具到Dockerfile确保脚本正常运行
- 解决Docker镜像部署时找不到配置文件的问题

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
shaw
2025-07-19 01:54:55 +08:00
parent 883a0f8c2d
commit 5d4b39b7a7
2 changed files with 79 additions and 0 deletions

View File

@@ -3,6 +3,84 @@ set -e
echo "🚀 Claude Relay Service 启动中..."
# 生成随机字符串的函数
generate_random_string() {
length=$1
# 使用 /dev/urandom 生成随机字符串
tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c $length
}
# 检查并复制配置文件
if [ ! -f "/app/config/config.js" ]; then
echo "📋 检测到 config.js 不存在,从模板创建..."
if [ -f "/app/config/config.example.js" ]; then
cp /app/config/config.example.js /app/config/config.js
echo "✅ config.js 已创建"
else
echo "❌ 错误: config.example.js 不存在"
exit 1
fi
fi
# 检查并创建 .env 文件
if [ ! -f "/app/.env" ]; then
echo "📋 检测到 .env 不存在,从模板创建..."
if [ -f "/app/.env.example" ]; then
cp /app/.env.example /app/.env
# 生成随机的 JWT_SECRET (64字符)
if [ -z "$JWT_SECRET" ]; then
JWT_SECRET=$(generate_random_string 64)
echo "🔑 生成 JWT_SECRET"
fi
# 生成随机的 ENCRYPTION_KEY (32字符)
if [ -z "$ENCRYPTION_KEY" ]; then
ENCRYPTION_KEY=$(generate_random_string 32)
echo "🔑 生成 ENCRYPTION_KEY"
fi
# 更新 .env 文件中的密钥
sed -i "s/JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" /app/.env
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${ENCRYPTION_KEY}/" /app/.env
# 设置 Redis 配置以连接到容器内的 Redis
sed -i "s/REDIS_HOST=.*/REDIS_HOST=redis/" /app/.env
echo "✅ .env 已创建并配置"
else
echo "❌ 错误: .env.example 不存在"
exit 1
fi
else
echo "✅ 检测到已有 .env 文件"
# 确保环境变量中有必要的密钥
if [ -z "$JWT_SECRET" ]; then
# 从 .env 文件读取
JWT_SECRET=$(grep "^JWT_SECRET=" /app/.env | cut -d'=' -f2)
if [ -z "$JWT_SECRET" ] || [ "$JWT_SECRET" = "your-jwt-secret-here" ]; then
JWT_SECRET=$(generate_random_string 64)
sed -i "s/JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" /app/.env
echo "🔑 更新 JWT_SECRET"
fi
fi
if [ -z "$ENCRYPTION_KEY" ]; then
# 从 .env 文件读取
ENCRYPTION_KEY=$(grep "^ENCRYPTION_KEY=" /app/.env | cut -d'=' -f2)
if [ -z "$ENCRYPTION_KEY" ] || [ "$ENCRYPTION_KEY" = "your-encryption-key-here" ]; then
ENCRYPTION_KEY=$(generate_random_string 32)
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${ENCRYPTION_KEY}/" /app/.env
echo "🔑 更新 ENCRYPTION_KEY"
fi
fi
fi
# 导出环境变量
export JWT_SECRET
export ENCRYPTION_KEY
# 检查是否需要初始化
if [ ! -f "/app/data/init.json" ]; then
echo "📋 首次启动,执行初始化设置..."