有没有办法直接从 Dockerfile 初始化/启动/继续运行 PostgreSQL 数据库?我有以下 Dockerfile。
# syntax = docker/dockerfile:1.4.0
FROM redhat/ubi8:latest
# Install a custom modified version of PostgreSQL 11
RUN dnf install myprecious-postgresql
# Prepare for PostgreSQL
ARG psqldb=/opt/myprecious/pg/var/lib/pgsql/11
ENV PGDATA=${psqldb}/data
RUN install -d -m 0755 /var/lock/subsys
RUN install -d -m 0755 -o postgres -g postgres ${psqldb}
RUN /etc/init.d/postgresql-${psqlversion} stop
RUN /etc/init.d/postgresql-${psqlversion} initdb
RUN /etc/init.d/postgresql-${psqlversion} start
USER postgres
RUN <<EOF cat >> /tmp/init.sql
CREATE USER hello WITH PASSWORD 'world';
CREATE DATABASE helloworld OWNER hello;
\c helloworld
UPDATE pg_language SET lanpltrusted=true WHERE lanname='c';
GRANT ALL ON LANGUAGE c TO hello;
EOF
RUN until /opt/myprecious/pg/bin/pg_isready; do sleep 1; done;
RUN psql -f init.sql
问题:
有没有办法让 PostgreSQL 在步骤之间保持运行?
=> 不。 Dockerfile 中步骤的想法是准备镜像
你需要像 init.sql 这样的东西
Dockerfile
FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/
在
init.sql
中,如果您第一次运行容器,则可以将逻辑放在空数据库上运行,如果数据库已经初始化,则在下一次容器启动时,init.sql
的运行将被跳过
在此处查看更多详细信息 如何在 Docker Postgres 脚本中创建用户/数据库
找到了一种在步骤之间运行 PostgreSQL 操作的方法。基本上我只需要重新启动数据库并等待它出现,然后再在其上运行任何内容。
将以下代码复制到将在步骤中运行的脚本中:
psqlversion=11
pg_initd=/etc/init.d/postgresql-$psqlversion
# We need to start postgresql again before modifying the PostgreSQL DB
# since every RUN command in Dockerfile is like a snapshot
$pg_initd start
until /opt/carillon/pg/bin/pg_isready; do sleep 1; done;
上述代码片段之后的任何内容,PostgreSQL 都将可用。