DEV Community

Kate Travers
Kate Travers

Posted on

3

How to Run Ecto Migrations on Production

You'd think the answer to this question would be a simple Google search away. Unfortunately, that wasn't the case for me this afternoon, working on a Phoenix project with a newly-added Ecto backend. In an effort to save others (and let's be honest, future me) the same frustration, here's the most straight-forward solutions I found.

What Doesn't Work

Mix. Mix tasks aren't compiled into your deployed release, and as evidenced in this exciting discussion, there's no plans to change this any time soon.

So don't try using your trusty local mix ecto.migrate task on production. Not gonna help you here.

What Does Work

1. Ecto.Migrator

Ecto ships with Ecto.Migrator, a first-class module for Ecto's migration API.

Run it manually by ssh'ing onto your app server, attaching to your Phoenix app, and running the following:

path = Application.app_dir(:my_app, "priv/repo/migrations")

Ecto.Migrator.run(MyApp.Repo, path, :up, all: true)
Enter fullscreen mode Exit fullscreen mode

Ideally, you'd wrap up the above in its own task that can be called during your build and deployment process. Check out Plataformatec's blog for a nice example.

2. eDeliver

Our app uses edeliver for deployments, and it has a super handy command for manually running migrations:

mix edeliver migrate production
Enter fullscreen mode Exit fullscreen mode

If we peek at the source, turns out this command actually just wraps up Ecto.Migrator for you, saving some precious keystrokes.

To run successfully, you'll need to add ECTO_REPOSITORY="MyApp.Repo" to your .deliver/config file.

Again, Plataformatec has a nice blog post on deploying your Elixir app with eDeliver.

Summary

Hi future me! Hope this post was still helpful the nth time around.

References:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
atyborska93 profile image
Angelika Cathor

Thank you for this! Saved me a lot of time.

In case somebody is looking for a way to rollback the last migration, just like I was, you need to pass those options to Ecto.Migrator:

Ecto.Migrator.run(MyApp.Repo, path, :down, step: 1)
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more