2

I've created docker image with PostgreSQL running inside and exposing 5432 port. This image doesn't contain any database inside. Container is an empty PostgreSQL database server.

I'd like in (or during) "docker run" command:

  • attach db file
  • create db via sql query execution
  • restore db from dump

I don't want to keep the data after container will be closed. It's just a temporary development server.

I suspect it's possible to keep my "docker run" command string quite short/simple.

Probably there it is possible to mount some external folder with db/sql/dump in run command and then create db during container initialization.

What are the best/recommended way and the best practices to accomplish this task? Probably somebody can point me to corresponding docker examples.

1
  • 1
    You can't "attach a db file" in Postgres - at least not in a reliable way. Restoring a dump using pg_restore is probably the most robust and fastest solution. Commented Jul 18, 2016 at 11:54

1 Answer 1

2

This is a good question and probably something other folks asked themselves more than once.

According to the docker guide you would not do this in a RUN command. Instead you would create yourself an ENTRYPOINT or CMD in your Dockerfile that calls a custom shell script instead of calling the postgres process direclty. In this scenario the DB would be created in a "real" filesystem, but then cleaned-up during shutdown of the container.

How would this work? The container would start, call the ENTRYPOINT or CMD as usual and consume the init script to get the DB filled. Then at the moment the container is stopped, the same script will be notified with a signal and manually drop the database content.

CMD ["cleanAndRun.sh"]

A sketched script "cleanAndRun.sh" taken from the Docker documentation and modified for your needs. Please remember it is a sketch only and needs modifications:

#!/bin/sh

# The script that is called in the trap must also stop the DB, so below call to
# dropdb is not enough, it just demonstrates how to call anything in the stop-container scenario!
trap "dropdb <params>" HUP INT QUIT TERM

# init your DB -every- time container starts
<init script to import to clean and import dump>

# start your postgres DB
postgres

echo "exited $0"
Sign up to request clarification or add additional context in comments.

Comments

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.