是否可以在创建映像时初始化数据库,而不是在启动容器时初始化?

问题描述 投票:0回答:1

是否可以在创建映像时创建我的自定义数据库(docker image build --tag mydb:latest)?如果我将sql文件放到“ /docker-entrypoint-initdb.d/”数据库,则每次从该映像启动容器时都会执行。我不想每次启动都运行数据库脚本,因为它很大数据库。

这是用于自动测试。如果我绑定该卷,则数据库将变为持久性。我也不想要因为我的测试用例会失败。

这是我的Dockerfile

FROM postgres:10
COPY seed.sql         /tmp/
COPY init-db.sh       /tmp/
WORKDIR /tmp/
RUN ["chmod", "+x", "init-db.sh"]
RUN ./init-db.sh

这是我的init-db.sh

#!/bin/bash
set -e
RETRIES=5
cd /usr/lib/postgresql/10/bin/
gosu postgres initdb
su postgres -c './pg_ctl start -D "/var/lib/postgresql/data"'
until psql -U postgres -d postgres -c "select 1" > /dev/null 2>&1 || [ $RETRIES -eq 0 ]; do
  echo "Waiting for postgres server, ${RETRIES}-- remaining attempts..."
  RETRIES=$((RETRIES--))
  sleep 1
done

psql -v ON_ERROR_STOP=1 -U postgres <<-EOSQL
    \i /tmp/seed.sql;
EOSQL

在Dockerfile和init-db.sh上面使用,我可以看到我在创建映像时执行了数据库。但是,当我用该映像启动容器时,看不到seed.sql创建的数据库。那么如何使用自己的数据库创建自己的“ postgres docker image”?

postgresql docker docker-compose dockerfile psql
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.