如何在构建 Docker 镜像时恢复 Postgresdump?

mil*_*ose 2 postgresql database-backups docker

我试图避免在我的工作流程中触及共享开发数据库;为了使这更容易,我想在我的磁盘上为我需要的模式定义 Docker 镜像。然而,我在制作一个 Dockerfile 时遇到了困难,该文件将创建一个已恢复转储的 Postgres 映像。我的问题是在构建 Docker 映像时,Postgres 服务器没有运行。

在 shell 中的容器中乱搞时,我尝试手动启动容器,但我不确定这样做的正确方法是什么。/docker-entrypoint.sh似乎什么也没做,我不知道如何“正确”启动服务器。

所以我需要做的是:

  • 以“FROM postgres”开头
  • 将转储文件复制到容器中
  • 启动PG服务器
  • 运行psql以恢复转储文件
  • 杀死PG服务器

(我不知道的步骤用斜体表示,其余的很容易。)

我想避免的是:

  • 在现有容器中手动运行恢复,整个想法是能够在不同的数据库之间切换,而无需接触应用程序配置。
  • 保存恢复的映像,我希望能够使用不同的转储轻松地为数据库重建映像。(另外,不可重复的镜像构建也不是 Docker 的感觉。)

小智 5

这可以通过提供 example.pg 转储文件使用以下 Dockerfile 来完成:

FROM postgres:9.6.16-alpine

LABEL maintainer="lu@cobrainer.com"
LABEL org="Cobrainer GmbH"

ARG PG_POSTGRES_PWD=postgres
ARG DBUSER=someuser
ARG DBUSER_PWD=P@ssw0rd
ARG DBNAME=sampledb
ARG DB_DUMP_FILE=example.pg

ENV POSTGRES_DB launchpad
ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD ${PG_POSTGRES_PWD}
ENV PGDATA /pgdata

COPY wait-for-pg-isready.sh /tmp/wait-for-pg-isready.sh
COPY ${DB_DUMP_FILE} /tmp/pgdump.pg

RUN set -e && \
    nohup bash -c "docker-entrypoint.sh postgres &" && \
    /tmp/wait-for-pg-isready.sh && \
    psql -U postgres -c "CREATE USER ${DBUSER} WITH SUPERUSER CREATEDB CREATEROLE ENCRYPTED PASSWORD '${DBUSER_PWD}';" && \
    psql -U ${DBUSER} -d ${POSTGRES_DB} -c "CREATE DATABASE ${DBNAME} TEMPLATE template0;" && \
    pg_restore -v --no-owner --role=${DBUSER} --exit-on-error -U ${DBUSER} -d ${DBNAME} /tmp/pgdump.pg && \
    psql -U postgres -c "ALTER USER ${DBUSER} WITH NOSUPERUSER;" && \
    rm -rf /tmp/pgdump.pg

HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
  CMD pg_isready -U postgres -d launchpad
Run Code Online (Sandbox Code Playgroud)

其中wait-for-pg-isready.sh是:

#!/bin/bash
set -e

get_non_lo_ip() {
  local _ip _non_lo_ip _line _nl=$'\n'
  while IFS=$': \t' read -a _line ;do
    [ -z "${_line%inet}" ] &&
        _ip=${_line[${#_line[1]}>4?1:2]} &&
        [ "${_ip#127.0.0.1}" ] && _non_lo_ip=$_ip
    done< <(LANG=C /sbin/ifconfig)
  printf ${1+-v} $1 "%s${_nl:0:$[${#1}>0?0:1]}" $_non_lo_ip
}

get_non_lo_ip NON_LO_IP
until pg_isready -h $NON_LO_IP -U "postgres" -d "launchpad"; do
  >&2 echo "Postgres is not ready - sleeping..."
  sleep 4
done

>&2 echo "Postgres is up - you can execute commands now"
Run Code Online (Sandbox Code Playgroud)

对于两个“不确定的步骤”:

启动PG服务器

nohup bash -c "docker-entrypoint.sh postgres &" 可以照顾它

杀死PG服务器

真的没有必要

以上脚本以及更详细的自述文件可在https://github.com/cobrainer/pg-docker-with-restored-db 获得