source: https://crondev.com/persistent-postgresql-inside-docker/
Most recommended way to persist data inside docker is to create data only container. However to simplify things it is also possible just to mount a directory from the host and to use that location as persistent storage. Also, this way it is easy enough to dockerize existing Postgres installations.
For existing postgres installations here are some preparation steps (Ubuntu 14.04 with postgres 9.3):
Stop postgres if running:
sudo stop postgresql
Copy data directory to new location, for testing purposes:
sudo cp -r /var/lib/postgresql /var/lib/postgresql-docker
Here is the Dockerfile I used:
FROM komljen/ubuntu
ENV PG_VERSION 9.3
ENV USER docker
ENV PASS SiHRDZ3Tt13uVVyH0ZST
ENV PGDATA /var/lib/postgresql/$PG_VERSION/main
ENV PGRUN /var/run/postgresql
RUN \
echo "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list && \
curl -sL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
| apt-key add - && \
apt-get update && \
apt-get -y install \
postgresql-${PG_VERSION} \
postgresql-contrib-${PG_VERSION} && \
rm -rf /var/lib/apt/lists/*
RUN \
echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/${PG_VERSION}/main/pg_hba.conf && \
echo "listen_addresses='*'" >> /etc/postgresql/${PG_VERSION}/main/postgresql.conf
COPY start.sh start.sh
EXPOSE 5432
RUN rm /usr/sbin/policy-rc.d
CMD ["/start.sh"]
And a start bash script:
#!/usr/bin/env bash
#===============================================================================
CONF="/etc/postgresql/${PG_VERSION}/main/postgresql.conf"
POSTGRES="/usr/lib/postgresql/${PG_VERSION}/bin/postgres"
#-------------------------------------------------------------------------------
chown -R postgres /var/lib/postgresql
mkdir -p "${PGRUN}/${PG_VERSION}-main.pg_stat_tmp"
chown -R postgres $PGRUN
su postgres -c "/usr/lib/postgresql/${PG_VERSION}/bin/initdb"
echo "Creating superuser: ${USER}"
su postgres -c "${POSTGRES} --single -D ${PGDATA} -c config_file=${CONF}" <<EOF
CREATE USER $USER WITH SUPERUSER PASSWORD '$PASS';
EOF
#-------------------------------------------------------------------------------
exec su postgres -c "${POSTGRES} -D ${PGDATA} -c config_file=${CONF}"
#===============================================================================
This postgres container will create superuser which can be used to create other users and databases. Also it will try to initiate new database each time, but in case the data is already present it will fail, which is expected.
Now just build and run persistent postgres docker container:
sudo docker build -t cron/postgres .
sudo docker run -d --name test -v /var/lib/postgresql-docker:/var/lib/postgresql -v /var/run/postgresql-docker:/var/run/postgresql cron/postgres
Hope you enjoyed reading this blog post. Please leave a comment if encounter on any issues or to get some additional answers.
source: https://crondev.com/persistent-postgresql-inside-docker/