Use the Override ECS Docker Command to Run Database Migrations

Article summary

The AWS command-line interface offers a programmatic way to manage your ECS cluster from your local terminal or CI/CD pipelines. This API is powerful in many ways. I’ll show how you can use this API to run a database migration. It’s done by leveraging an existing task definition for a service running on your ECS cluster.

Implementation

The run-task command paired with the “–overrides” parameter can be a real boon for running one-off tasks. Using overrides allows you to change the default command for the container specified in your task definitions. For example, instead of running the command that starts your web server, you can have it run a database migration instead. The programming logic is simple:

  1. Query the AWS API to get the latest revision of the task definition you wish to override.
  2. Then, run a new task using that task definition, passing in overrides to change the default Docker command.

Code

Here’s the bash script I use to run database migrations for my Rails application. You can change the variables in the script to make it work for yours!

What’s cool is you can also tweak this script to run different Docker commands. This can be useful to roll back a migration, seed the database, or run a one-off script that requires the context of your application. There are many possibilities using run-task with overrides!