Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 48 ยท Real-World Elixir

Releases, Config and Deployment

Learn how to configure and ship an Elixir app: config files, runtime.exs, mix release, clustering basics and observability with Telemetry.

Running mix phx.server on your laptop is fine for development, but a production server should not need your source code, Mix or a compiler. Elixir solves this with releases: a self-contained directory with your compiled code, its dependencies and the Erlang runtime, started by a single script. A release also gives you a clear place to inject configuration, a way to run migrations and hooks for remote debugging.

This lesson covers the configuration files, mix release, how a typical deployment flows, a short look at clustering, and Telemetry, the standard way to observe a running system. The tooling cannot run on this site, so the Elixir and shell blocks are read-only; the editors model the configuration logic in JavaScript. Read Mix: Creating and Managing Projects first if the project layout is unfamiliar.

From code to production

Build mix release compiles and bundles.
Ship Copy one directory or image.
Run bin/my_app start boots the node.

The server needs no Mix and no source code.

1 / 2

Configuration: compile time versus runtime

Elixir has an application environment: a keyword store, read with Application.get_env/3, that holds settings for each OTP application. Where you set values matters.

  • config/config.exs is evaluated at compile time, before your code is compiled. It sets defaults shared by all environments and ends by importing an environment file with import_config "#{config_env()}.exs".
  • config/dev.exs, config/test.exs and config/prod.exs hold per-environment values. They are also compile time.
  • config/runtime.exs is evaluated every time the system boots, including from a release, in every environment. This is where production secrets and hostnames belong.

The rule of thumb: anything that differs between deployments (database URL, secret key, port, hostname) goes in runtime.exs, read from environment variables. If you put it in prod.exs, the value is baked into the build, and you must rebuild to change it.

ELIXIR
# config/runtime.exs
import Config

if config_env() == :prod do
  database_url =
    System.get_env("DATABASE_URL") ||
      raise "environment variable DATABASE_URL is missing"

  config :my_app, MyApp.Repo,
    url: database_url,
    pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")

  config :my_app, MyAppWeb.Endpoint,
    http: [port: String.to_integer(System.get_env("PORT") || "4000")],
    secret_key_base:
      System.get_env("SECRET_KEY_BASE") ||
        raise("environment variable SECRET_KEY_BASE is missing")
end

Failing with raise when a required variable is missing is deliberate. A node that refuses to boot with a clear message is much better than one that starts with a wrong default. This is "let it crash" applied to configuration, as in Links, Monitors and Let It Crash.

Never commit secrets. Phoenix generates prod secrets for you with mix phx.gen.secret, and your platform injects them as environment variables.

Reading config in code

ELIXIR
Application.get_env(:my_app, :greeting, "hello")   # with a default
Application.fetch_env!(:my_app, :api_key)          # raises if missing

Use fetch_env!/2 for required settings, so a missing one fails loudly. Avoid Application.get_env in module attributes (@key Application.get_env(...)): that is evaluated at compile time and will silently ignore runtime.exs. Read the value inside a function instead.

A model of runtime config

The editor below mimics what runtime.exs does: it reads an environment object, applies defaults, converts types and fails when a required key is missing. It is a JavaScript stand-in for the logic, not the Elixir Config module.

JS Runtime configuration with defaults and required keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Building a release

Releases are built with Mix. In a Phoenix project, you first compile with production settings, build the assets and then run the release task:

Terminal
MIX_ENV=prod mix deps.get --only prod
MIX_ENV=prod mix compile
MIX_ENV=prod mix assets.deploy
MIX_ENV=prod mix release

The result lands in _build/prod/rel/my_app/. It contains your compiled modules, all dependencies and a copy of the Erlang runtime (ERTS), so the target machine needs no Elixir install, but it must have a compatible operating system and CPU architecture. Building inside a Docker image or CI job that matches production is the safe approach.

The bin/my_app script is the control interface:

Terminal
bin/my_app start          # run in the foreground
bin/my_app daemon         # run in the background
bin/my_app remote         # open an IEx shell on the running node
bin/my_app rpc "IO.puts(:hello)"   # run an expression on the running node
bin/my_app stop

remote is a big reason to love releases: you can inspect a live system, with its real state, without restarting it. Use it carefully on production.

Migrations without Mix

Mix is not in a release, so Phoenix generates a module such as MyApp.Release with a function that calls Ecto.Migrator. You run it with bin/my_app eval "MyApp.Release.migrate()". A deploy usually runs the migration, then starts the new version.

Release options

Options live in mix.exs under releases:, for example which applications to include or whether to produce a tarball. The defaults are fine to start with. Files in rel/ (such as env.sh.eex and vm.args.eex) let you tune runtime flags, the node name and the cookie.

A typical deployment flow

flowchart LR
    A["Git push"] --> B["CI: test"]
    B --> C["Build release<br/>(Docker image)"]
    C --> D["Run migrations"]
    D --> E["Start new version"]
    E --> F["Health check passes"]

Build once in an environment that matches production, migrate, start, then check health.

Common targets are a container platform, a virtual machine with a systemd unit, or a PaaS that supports Docker. Whichever you pick, the release is the same artifact. Add a health-check route that returns 200 only when the app can reach its database, and let your load balancer use it.

Clustering overview

Erlang nodes can connect to each other and send messages across the network as if the processes were local. A cluster is a set of connected nodes. You get this almost for free: nodes need a name, a shared secret cookie and network access between them.

ELIXIR
Node.connect(:"[email protected]")
Node.list()   # other nodes this node is connected to

In practice you rarely connect by hand. The libcluster library discovers peers (through DNS, Kubernetes or a cloud API) and connects them. Once connected, Phoenix.PubSub broadcasts reach subscribers on every node, so a LiveView on one server hears events published on another.

Clustering also brings responsibilities. Distribution is not encrypted by default, and the cookie is only a weak shared secret, so keep the cluster on a private network. Remember that a plain GenServer name is local to one node unless you use something that is cluster-aware. For many apps a single node or a few independent nodes behind a load balancer is enough, and you only cluster when you need cross-node messaging.

Observability with Telemetry

You cannot fix what you cannot see. The BEAM ecosystem uses Telemetry, a tiny library that standardizes events. Libraries such as Phoenix, Ecto and Plug emit events like "a request finished" or "a query finished", each with measurements (durations) and metadata (the route, the table). Your code attaches handlers.

ELIXIR
:telemetry.attach(
  "log-slow-queries",
  [:my_app, :repo, :query],
  fn _event, measurements, metadata, _config ->
    ms = System.convert_time_unit(measurements.total_time, :native, :millisecond)

    if ms > 200 do
      Logger.warning("slow query (#{ms} ms): #{metadata.query}")
    end
  end,
  nil
)

You can emit your own events with :telemetry.execute/3:

ELIXIR
:telemetry.execute([:my_app, :orders, :created], %{count: 1}, %{currency: "EUR"})

A Phoenix project generates a Telemetry supervisor with Telemetry.Metrics definitions (counters, summaries, last values), and reporters send them to a dashboard such as LiveDashboard, Prometheus or an APM service. Add structured logging (Logger metadata such as a request id) and error reporting for a complete picture.

The model below shows the shape of the idea: handlers registered by event name, and an execute function that calls them.

JS A tiny Telemetry model

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The emitting code does not know who listens. That decoupling is why libraries can be instrumented without depending on your monitoring tool.

Deployment checklist

  • Set PHX_SERVER=true (or run bin/server if generated) so a Phoenix release starts the web endpoint.
  • Provide every variable that runtime.exs requires.
  • Build in an environment that matches production's OS and architecture.
  • Run migrations as a separate step before starting the new version.
  • Add a health check, logs in a structured format and a way to reach bin/my_app remote.
  • Plan for restarts: supervision trees bring the app back, and the process manager restarts the node itself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should the production database URL be read from?

    runtime.exs is evaluated each time the release boots, so values can change without rebuilding. Compile-time files bake the value into the build.
  2. 2. What does a release contain?

    A release is a self-contained directory with compiled modules, dependencies and ERTS, so the target needs no Elixir install.
  3. 3. Why does runtime.exs often raise when a variable is missing?

    Booting with a wrong default is worse than refusing to start. Failing fast makes the problem obvious.
  4. 4. What is Telemetry used for?

    Libraries emit events with measurements and metadata, and handlers or reporters turn them into logs and metrics.
  5. 5. Which command opens a shell on a running release?

    bin/my_app remote connects an IEx session to the running node, which is useful for inspection.

Summary

  • A release bundles compiled code, dependencies and ERTS, and needs no Mix on the server.
  • config.exs and the environment files are compile time; runtime.exs runs at every boot and is the place for secrets and hostnames.
  • Fail fast on missing required settings, and use Application.fetch_env!/2 for required values.
  • Build with MIX_ENV=prod mix release, run migrations via eval, and inspect live nodes with remote.
  • Clusters connect nodes with a name and cookie; keep them on a private network.
  • Telemetry events decouple instrumentation from reporting.

Next up: Performance and Common Pitfalls.