#!/bin/sh # wait for db # ... if bundle exec rails db:exists ; then echo 'Running database migrations...' bundle exec rails db:migrate else echo 'Creating and seeding application database...' bundle exec rails db:create bundle exec rails db:migrate bundle exec rails db:seed fi # other startup commands # ... bundle exec rails server -b 0.0.0.0
Ruby on Rails Docker CMD Startup Script
CMD startup script for a containerized Ruby on Rails project to create or migrate the project database then start the application server.
The script requires the custom rake task
db:exists. Make sure the task is added to the project repository and copied into the container image in the Dockerfile.
Details of the rake task can be found here: Check if Ruby On Rails Database Exists Using Rake
Add Script to Repository
Add script to the project repository under a suitable directory and filename, for example:
Ensure the script file is executable:
sudo chmod +x ./.docker/scripts/app-startup.sh
Wait for Database to be Ready
Add a command at the top of the script which waits for the database to be ready. This is database specific, for example, for MySQL:
# wait for db until mysqladmin ping -h "$DB_HOST" --silent ; do sleep 1 done
# wait for db until pg_isready -U "$DB_USERNAME" -h "$DB_HOST" ; do sleep 1 done
Make sure the relevant environment variables such as
DB_HOST are available in the container.
Add Additional Startup Commands
Add any additional required startup commands to the script, for example generating a sitemap using the sitemap_generator gem:
bundle exec rails sitemap:refresh:no_ping
Add and Run in Dockerfile
Make sure the script file is copied into the container image in the Dockerfile.
Run the script as the default command in the Dockerfile using the
CMD instruction, for example: