我需要用entrypoint来判断数据库是否可用,表是否存在。
我使用以下 shell 来确定表是否存在
部分dockerfile内容
ENTRYPOINT ["bash","docker-entrypoint.sh"]
Shell脚本内容
until PGPASSWORD=postgres psql -h "db" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
# Prepare variables
TABLE=web_user
SQL_EXISTS=$(printf '\dt "%s"' "$TABLE")
# Credentials
USERNAME=postgres
PASSWORD=postgres
DATABASE=postgres
echo "Checking if table <$TABLE> exists ..."
# Check if table exists
PGPASSWORD="$PASSWORD" psql -h "db" -U $USERNAME -d $DATABASE -c "$SQL_EXISTS"
# using #!/bin/bash
if [[ $(PGPASSWORD="$PASSWORD" psql -h "db" -U $USERNAME -d $DATABASE -c "$SQL_EXISTS") ]]
then
echo "Table exists ..."
else
echo "Table not exists ..., init database"
python3 manage.py makemigrations web
python3 manage.py migrate
fi
db
is theservice name
of the postgres container in compose
我想要的是容器第一次启动,判断user表不存在,然后新建一个数据库
,然后重启容器,发现user表已经存在无需创建新的数据表
但是当我在 Ubuntu16.04 基础镜像上使用它时,它只是输出 table exists...
容器第一次启动
psql: FATAL: the database system is starting up
Postgres is unavailable - sleeping
Checking if table <web_user> exists ...
No matching relations found.
Table exists ...
但我期望的是打印table not exists..., the init database
和后续命令
使用python alpine
基础镜像的输出如下
Checking if table <web_user> exists ...
Did not find any relation named ""web_user"".
Table not exists ..., init database
Migrations for 'web':
区别如下:
没有找到匹配关系。
是基于ubuntu镜像
的输出,
根据
python:3.6.9-alpine image
为什么不是 else 部分呢?
如果你能告诉我为什么会出现这个错误以及如何解决它,我将不胜感激?
最佳答案
我的猜测是 if 语句为真,因为您已成功连接到数据库(并且与该连接是否找到字符串无关)
像这样试试:
if [[ $(PGPASSWORD="$PASSWORD" psql -h "db" -U $USERNAME -d $DATABASE) ]]
then
echo connection successful
echo basing your previous if on:
echo $(PGPASSWORD="$PASSWORD" psql -h "db" -U $USERNAME -d $DATABASE -c "$SQL_EXISTS")
fi
https://stackoverflow.com/questions/61060674/
相关文章:
http - flutter x-www-form-urlencoded POST 请求
android - performAction() 中的 SCROLL_TO_POSITION 返回
azure-devops - 已邀请用户 Azure Devops 项目,但他们无法访问它
azure-devops - Azure DevOps VsTest 任务失败且没有错误
python-3.x - 刚刚切换到 TensorFlow 2.1 并收到一些烦人的警告
python - 如何处理 Python 中不同模块的相关对象之间的循环引用?
django - HTTPConnectionPool(主机 ='0.0.0.0',端口=5000)
python - Django 和 MongoDB 在 Django 模型上的默认 ID autoF