postgresql:dockerfile 从入口点脚本创建用户和数据库

postgresql: dockerfile create user and database from entrypoint script

我有一个 Dockerfile

COPY ./docker-entrypoint.sh /

RUN chmod +x /docker-entrypoint.sh

USER postgres

ENTRYPOINT ["/docker-entrypoint.sh"]

其中 docker-entrypoint.sh 是:

#!/bin/sh

# Before PostgreSQL can function correctly, the database cluster must be initialized:
initdb -D /var/lib/postgres/data


#start postgres server
/usr/bin/postgres -D /var/lib/postgres/data &


# create a user or role
psql -d postgres -c "CREATE USER someuser WITH PASSWORD 'jkhkjah';" 

# create database 

psql -d postgres -c "CREATE DATABASE dockertest OWNER 'someuser';"

它不会创建一些用户和 dockertest 数据库。怎么做

看看 official docker postgresql image

它有这样的工作流程:

  1. 执行docker-entrypoint.sh
  2. 启动 postgresql 服务器

所以你需要像这样修改你的 Dockerfile:

COPY ./docker-entrypoint.sh /

RUN chmod +x /docker-entrypoint.sh

USER postgres

ENTRYPOINT ["/docker-entrypoint.sh"]

EXPOSE 5432
CMD ["postgres"]

然后像这样修改你的docker-entrypoint.sh:

#!/bin/sh

# Before PostgreSQL can function correctly, the database cluster must be initialized:
initdb -D /var/lib/postgres/data

# internal start of server in order to allow set-up using psql-client
# does not listen on external TCP/IP and waits until start finishes
pg_ctl -D "/var/lib/postgres/data" -o "-c listen_addresses=''" -w start

# create a user or role
psql -d postgres -c "CREATE USER someuser WITH PASSWORD 'jkhkjah';" 

# create database 
psql -v ON_ERROR_STOP=1 -d postgres -c "CREATE DATABASE dockertest OWNER 'someuser';"

# stop internal postgres server
pg_ctl -v ON_ERROR_STOP=1 -D "/var/lib/postgres/data" -m fast -w stop

exec "$@"

我认为你的主要错误是在后台启动 postgresql

/usr/bin/postgres -D /var/lib/postgres/data &

并在服务器启动之前立即开始执行查询。

我还建议向 psql 添加 -v ON_ERROR_STOP=1 参数,以查看详细信息并在发生错误时停止进程