skip to content
Lean Miguel

Run Processes on Elixir Startup

/ 1 min read

Elixir doesn’t have an entrypoint like Go where it runs the main function when the executable is run. In Elixir’s case, you implement the Application behavior in your module and add it to the application function in your mix.exs file.

Below is an example of how this works with an HTTP server such as Bandit.

# lib/bandit_server.ex
defmodule Example.BanditServer do
  use Application

  def start(_type, _args) do
    children = [
      {Bandit, plug: MyRouter, scheme: :http, port: 4001}
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]

    Supervisor.start_link(children, opts)
  end
end

# mix.exs
defmodule Example.MixProject do
  use Mix.Project
  ...
    
  def application do
    [
      mod: {Example.BanditServer, []}
    ]
  end

end

When you run iex -S mix now, it will start the Bandit HTTP server right away. This is in contrast to running iex -S mix and then manually calling and managing the pid of Example.BanditServer.start to start your application.