0

I am wondering how I can check whether the DB already exists before trying to create it in the following Docker built line. At the moment, it does not let the build to proceed because the DB has already been created once.

RUN set -e && \
    nohup bash -c "docker-entrypoint.sh postgres &" && \
    /tmp/wait-for-pg-is-ready.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.pgdump && \
    psql -U postgres -c "ALTER USER ${DBUSER} WITH NOSUPERUSER;" && \
    rm -rf /tmp/pgdump.pgdump
MadPhysicist
  • 5,401
  • 11
  • 42
  • 107
  • 1
    When I `docker pull` this image and run it on my system, this `RUN` line won't have affected the database I have here. There are also some technical reasons this won't work. I'd suggest creating a database and user when you create the database container; configuring the application with the relevant credentials; and either running migrations manually or automatically to create tables. – David Maze Oct 09 '22 at 22:41
  • You would not normally create a database when *building* a image; this is something generally more appropriate at runtime. If you're basing your image on the official postgres image, this may not even work -- the database files are stored on an ephemeral volume and won't persist in the final image. – larsks Oct 09 '22 at 22:42
  • I was going off the discussion here: https://stackoverflow.com/questions/48643774/how-to-restore-a-postgresdump-while-building-a-docker-image – MadPhysicist Oct 09 '22 at 22:45
  • @DavidMaze Isn't that what I am doing here? I am probably in a bit over my head :/ – MadPhysicist Oct 09 '22 at 22:46
  • @larsks I was trying to get to where I end up with a running container, that contained a restored DB from a file I provided. What is the accepted way to do that? – MadPhysicist Oct 09 '22 at 22:50
  • 1
    I suggest you move your `RUN` section into container's `entrypoint` so that your database will be built when you run the image. – Philippe Oct 09 '22 at 23:08

0 Answers0