Executing scripts inside Elixir releases

almirsarajcic

almirsarajcic

Created 23 days ago

Inside the default runner Docker image provided by Phoenix Elixir is not available, so we can’t execute something like elixir priv/script.exs. But we can load the file using Code.load_file/1.

Here’s how it’s done.

# SSH into the machine
fly ssh console # on Fly.io
kamal app exec --reuse -i bash # on Kamal

# Connect via a remote shell
bin/my_app remote

# Execute the script
iex> Code.load_file(Path.join([:code.priv_dir(:my_app), "script.exs"]))

Note that Mix is not available inside releases, so you won’t be able to install dependencies using Mix.install/1. Instead, you’ll have to include them in your mix.exs file or avoid using them entirely.

To keep this in your terminal’s history, you could SSH into the machine and execute the script all in one step:

# on Fly.io
fly ssh console \
    -C "bin/my_app rpc 'Code.load_file(Path.join([:code.priv_dir(:my_app), \"script.exs\"]))'"

# on Kamal
kamal app exec --reuse \
    -i "bin/my_app rpc 'Code.load_file(Path.join([:code.priv_dir(:my_app), \"script.exs\"]))'"