You can configure a release command depending on the platform you are using to deploy your Phoenix application. For example, you can use Fly’s release_command.
If you don’t have the option to specify a release command, you can use a bash script for this purpose.
When you run mix phx.gen.release --docker
, there will be two scripts generated under rel/overlays/bin
and one elixir
module containing tasks for running migrations under lib/app_name/release.ex
.
The bin/migrate
script calls MyApp.Release.migrate
to run the DB migrations.
The bin/server
script starts the server using the released binary my_app
.
You can create a new script that runs the migration command (Release
module) and then starts the server.
Let’s create it under rel/overlays/bin/migrate_and_server
.
#!/bin/sh
cd -P -- "$(dirname -- "$0")"
# Run migrations. If they fail, don't start the server
./migrate && exec ./server
Now, modify the generated Dockerfile CMD (last line) to:
CMD ["/app/bin/migrate_and_server"]
Done! You now have auto-migrations on every deployment. Don’t worry, if migrations are already applied it will continue to start your server as usual.