Phoenix Release Migrations from the command line

A blog post on the Plataformatec website uses the following code snippet for performing migrations in an Exrm release:

defmodule Release.Tasks do  
  def migrate do
    {:ok, _} = Application.ensure_all_started(:my_app)

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

    Ecto.Migrator.run(MyApp.Repo, path, :up, all: true)

    :init.stop()
  end
end  

Incidentally, the app may crash due to an eaddrinuse error, or something else related to the HTTP server making an attempt to start and failing because the server is already running.

Instead of terminating the server for migrations, it's better to modify the task to only load Ecto. The new task can be rewritten as follows:

defmodule Release.Tasks do  
  def migrate do
    {:ok, _} = Application.ensure_all_started(:ecto)
    {:ok, _} = Application.ensure_all_started(:postgrex)
    Application.load(:my_app)
    MyApp.Repo.start_link

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

    Ecto.Migrator.run(MyApp.Repo, path, :up, all: true)

    :init.stop()
  end
end  

The command in the terminal should now execute without errors:

rel/my_app/bin/my_app command Elixir.Release.Tasks migrate