Files
user_service/deploy/scripts/db-lanuch-entrypoint.sh
2025-10-09 18:19:57 +08:00

43 lines
1.6 KiB
Bash
Executable File
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.

#!/bin/sh
set -e # 脚本执行出错时立即退出
# --------------------------
# 1. 启动PostgreSQL服务后台运行
# --------------------------
# 调用PostgreSQL默认初始化逻辑即使数据目录已存在也会启动服务
docker-entrypoint.sh postgres &
# 记录PostgreSQL主进程ID后续等待用
PG_PID=$!
# --------------------------
# 2. 等待数据库服务就绪(避免脚本执行时数据库未启动)
# --------------------------
echo "等待PostgreSQL服务就绪..."
# 将所有参数放在同一行,避免换行解析问题
until pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" -h "localhost" -p "5432"; do
sleep 1 # 每1秒检查一次
done
echo "PostgreSQL服务已就绪开始强制执行脚本..."
# --------------------------
# 3. 强制执行所有挂载的SQL脚本每次启动都执行
# --------------------------
# 遍历/docker-entrypoint-initdb.d目录下的所有.sql脚本按文件名排序
for script in /docker-entrypoint-initdb.d/*.sql; do
if [ -f "$script" ]; then # 确保是文件(排除目录)
echo "正在执行脚本: $script"
# 用psql客户端执行脚本指定用户和数据库
psql -U "$POSTGRES_USER" \
-d "$POSTGRES_DB" \
-h "localhost" \
-p "5432" \
-f "$script" \
--set=ON_ERROR_STOP=1 # 脚本执行出错时停止(可选,根据需求调整)
echo "脚本执行完成: $script"
fi
done
# --------------------------
# 4. 等待PostgreSQL主进程避免容器启动后退出
# --------------------------
wait $PG_PID