Docker Compose + Rails: best practice to migrate? Docker Compose + Rails: best practice to migrate? docker docker

Docker Compose + Rails: best practice to migrate?


From https://docs.docker.com/engine/reference/builder/#cmd:

If you would like your container to run the same executable every time, then you should consider using ENTRYPOINT in combination with CMD. See ENTRYPOINT

https://docs.docker.com/engine/reference/builder/#entrypoint

tl;dr

You could define an entrypoint under app and define a bash file there:

app:  entrypoint: [bin/entry]  ..

bin/entry file example:

#!/bin/bashset -erake db:createrake db:migrateexec "$@"


This approach creates the database if the migration is not able to succeed. It also avoids the issue of being unable to start the server because a pid file was left behind. Create the file as app/lib/docker-entrypoint.sh.

#!/bin/sh# https://stackoverflow.com/a/38732187/1935918set -eif [ -f /app/tmp/pids/server.pid ]; then  rm /app/tmp/pids/server.pidfibundle exec rake db:migrate 2>/dev/null || bundle exec rake db:setupexec bundle exec "$@"

The docker-compose.yml then includes:

entrypoint: ["/app/lib/docker-entrypoint.sh"]command: ["rails","server","-b","0.0.0.0","-p","3000"]


I use a Makefile:

run:    docker-compose up -d \    && docker-compose run web rake db:create

So, now when I wanna docker-compose up I just do make run instead.