Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"correct" way to manage database schemas in docker

I'm developing an open source application consisting of a Java web application and a postgresql database. Ideally it would be deployable similar to the process detailed in the shipyard quickstart:

  1. run a data-only container
  2. run the DB container
  3. run the application container

Is there a recommended time to set up the database schema? I was thinking on making the Dockerfile for the database image create the schema when it is built but postgres isn't running at this time obviously.

like image 475
sjmeverett Avatar asked Feb 24 '15 16:02

sjmeverett


1 Answers

We use Postgres and Docker where I work and we ended up doing the following:

  1. Copy the Dockerfile from the official Postgres repo so you can make your own image.
  2. Modify docker-entrypoint.sh (https://github.com/docker-library/postgres/blob/8f80834e934b7deaccabb7bf81876190d72800f8/9.4/docker-entrypoint.sh), which is what is called when the container starts.

At the top of docker-entrypoint.sh, I put in the following:

# Get the schema
url=$(curl -s -u ${GIT_USER}:${GIT_PASSWORD} "${SQL_SCRIPT_URL}" | python -c 'import sys, json; print json.load(sys.stdin)["download_url"]')
curl ${url} > db.sh
chmod +x db.sh
cp db.sh ./docker-entrypoint-initdb.d

This basically downloads a shell script from Github that initializes the schema for the database. We do this to manage versions of the schema, so when you start your container you can tell it which schema to use via an ENV variable.

Some notes about the code:

  1. We need to refactor to pull stuff from Github using a private key instead of user credentials.
  2. The ./docker-entrypoint-initdb.d directory is a place where docker-entrypoint.sh will look to run init scripts for the database. You can move files to that location however you want. Do this if downloading from Github is not applicable.
like image 120
ryan1234 Avatar answered Oct 13 '22 10:10

ryan1234