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
6
  • 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. Commented Oct 9, 2022 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. Commented Oct 9, 2022 at 22:42
  • I was going off the discussion here: stackoverflow.com/questions/48643774/… Commented Oct 9, 2022 at 22:45
  • @DavidMaze Isn't that what I am doing here? I am probably in a bit over my head :/ Commented Oct 9, 2022 at 22:46
  • 1
    I suggest you move your RUN section into container's entrypoint so that your database will be built when you run the image. Commented Oct 9, 2022 at 23:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.