Migrating the Database
Explore effective techniques for migrating your Rails application's database in a Docker environment. Understand why using a one-shot service for migrations is preferred over entry-point scripts, how to handle service startup timing issues, and implement readiness checks with a wait-for script. By the end of this lesson, you will be able to ensure your database is fully migrated before your app launches, avoiding common pitfalls and enabling smoother production-like deployments.
Ways to migrate DB
The postgres image automatically creates the default database if it does not exist. However, currently, nothing ensures that the
migrations have been run. In development, we just did this manually by:
docker-compose exec web bin/rails db:migrate
Using .sh file
We need to ensure that our app has a fully migrated database when it launches. One way you might think of achieving this is with the entry-point concept we used to solve the server PID issue. We already have a docker-entrypoint.sh file that is run just prior to launching our app. This might lead you to try migrating the database as follows:
Why .sh won’t work?
Although it seems like this approach should work, unfortunately, it does not scale well. Were you to start three replicas of your app at the same time, each would try to migrate the database, which can lead to locking issues that prevent the app from starting. Another downside is that you cannot migrate the database independently; it is tied to the app launch. ...