Run deploy tasks in your Docker containers

So you want to migrate your database while deploying a new docker image into production? Learn how to easily do it by simply setting an environment variable.

Add the following to a file docker/deploy_tasks.sh in your Rails project.

#!/bin/bash
if [[ -n "$DEPLOY_TASKS" ]] ; then
  echo "Running deploy tasks: bundle exec rake $DEPLOY_TASKS"
  bundle exec rake $DEPLOY_TASKS
else
  echo "No deploy tasks set."
fi

Next I assume you’re using the phusion/passenger-docker image to build your app but any other will do as long it can run scripts during container startup.

Ad the following to your Dockerfile.

RUN mkdir -p /etc/my_init.d
ADD docker/deploy_tasks.sh /etc/my_init.d/deploy_tasks.sh

Now, simply add a DEPLOY_TASKS environment variable to your next deploy. For example db:migrate some:other_task and it will be done when starting the container.