Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Testing and Deployment

Releases, Configuration and Deployment

Deploy a Phoenix app: mix release, config/runtime.exs and environment variables, migrations in releases, Docker, health checks, clustering and zero-downtime tips.

Running mix phx.server on a laptop is fine for development. In production you build a release: a self-contained folder holding your compiled code, its dependencies and the Erlang runtime, started with one script. A release needs no Elixir, Mix or source code on the server, boots fast, and is the standard way to ship a Phoenix app.

Mix, Docker and a real server are not available on this site, so commands are read-only. The runnable editors model configuration loading and health checks in JavaScript.

Compile-time versus runtime configuration

This is the idea that trips up most people. Elixir config files run at different moments:

File Runs Use it for
config/config.exs at compile time, every environment settings that shape the build
config/dev.exs, test.exs, prod.exs at compile time, per environment environment defaults, never secrets
config/runtime.exs when the release boots (and on mix phx.server) secrets, hostnames, database URL, ports

Because a release is compiled once and then copied, anything that differs between servers must be read in runtime.exs from environment variables:

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"),
    ssl: true

  secret_key_base =
    System.get_env("SECRET_KEY_BASE") ||
      raise "environment variable SECRET_KEY_BASE is missing"

  host = System.get_env("PHX_HOST") || "example.com"
  port = String.to_integer(System.get_env("PORT") || "4000")

  config :my_app, MyAppWeb.Endpoint,
    url: [host: host, port: 443, scheme: "https"],
    http: [ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port],
    secret_key_base: secret_key_base
end

Raising when a variable is missing is deliberate: the release refuses to boot with a clear message instead of failing later in a confusing way. Generate the secret once with mix phx.gen.secret and store it in your host's secret manager. Never commit it (see web security).

Building a release

Phoenix can generate the helpers for you with mix phx.gen.release. The build steps are then:

Terminal
export MIX_ENV=prod
mix deps.get --only prod
mix compile
mix assets.deploy        # builds, minifies and digests CSS and JS
mix release

mix assets.deploy creates fingerprinted files and a manifest so browsers can cache them forever. The release lands in _build/prod/rel/my_app. You start it with bin/my_app start, or open a live remote console with bin/my_app remote.

Migrations without Mix

Mix is not present in a release, so run migrations through a module that calls Ecto directly. mix phx.gen.release creates it:

ELIXIR
defmodule MyApp.Release do
  @app :my_app

  def migrate do
    load_app()
    for repo <- repos() do
      {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
    end
  end

  def rollback(repo, version) do
    load_app()
    {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
  end

  defp repos, do: Application.fetch_env!(@app, :ecto_repos)
  defp load_app, do: Application.load(@app)
end

You run it before starting the new version: bin/my_app eval "MyApp.Release.migrate()". Write migrations so the old code still works against the new schema (add columns first, remove them in a later deploy); see Ecto schemas and migrations.

A Dockerfile

Most hosts accept a container. The usual pattern is a multi-stage build: compile in a full image, copy only the release into a small one.

DOCKERFILE
FROM hexpm/elixir:1.18.1-erlang-27.2-debian-bookworm-20241202-slim AS build
ENV MIX_ENV=prod
WORKDIR /app
RUN mix local.hex --force && mix local.rebar --force
COPY mix.exs mix.lock ./
RUN mix deps.get --only prod
COPY config config
RUN mix deps.compile
COPY priv priv
COPY lib lib
COPY assets assets
RUN mix assets.deploy && mix release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y libstdc++6 openssl libncurses6 && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /app/_build/prod/rel/my_app ./
ENV PHX_SERVER=true
CMD ["bin/my_app", "start"]

Version tags above are examples; use the versions you develop with. PHX_SERVER=true makes the release start the web server (the generated runtime.exs checks it). See the Docker tutorial for the container side.

Health checks and graceful restarts

Load balancers and orchestrators need to know when your app is ready. Add a cheap endpoint that does not need a session or a login, and a deeper one that touches the database:

ELIXIR
scope "/", MyAppWeb do
  get "/healthz", HealthController, :live     # process is up
  get "/readyz",  HealthController, :ready    # database reachable
end

During a deploy the old node receives SIGTERM; Phoenix stops accepting new connections and lets in-flight requests finish. LiveView and channel clients simply reconnect to a new node and remount, which is why a LiveView must rebuild its state from mount/3 (see the lifecycle).

Clustering

Several nodes can form a cluster so PubSub and Presence work across them (see PubSub). The dns_cluster library, included in new projects, discovers peers through a DNS name you set in DNS_CLUSTER_QUERY. Each node also needs a unique RELEASE_NODE name and a shared RELEASE_COOKIE. Without clustering, a broadcast on node A never reaches a viewer connected to node B.

Keep the Erlang cookie private and never expose the distribution port (4369 and the node ports) to the internet. Anyone who reaches it with the cookie can run code on your server.

Runnable models

The first model mimics runtime.exs: it reads the environment, supplies defaults for the harmless values and fails loudly for secrets.

Node.js runtime.exs style config loading (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second model is a rolling deploy behind a load balancer. The balancer sends traffic only to nodes whose readiness check passes, so users never see a node that is still migrating or shutting down.

Node.js Rolling deploy with readiness checks (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A deployment checklist

  • SECRET_KEY_BASE, DATABASE_URL, PHX_HOST and PORT come from the environment.
  • force_ssl and HSTS are on in production, behind a proxy that forwards the original protocol.
  • Assets are built with mix assets.deploy, served with long cache headers (or from a CDN).
  • Migrations run before the new version takes traffic and are backward compatible.
  • Logs go to stdout as structured lines; errors and telemetry go to a monitoring service.
  • A health endpoint exists, and the process manager restarts a crashed node.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which config file is evaluated when the release boots, making it the right place for secrets?

    config.exs and prod.exs are evaluated at compile time. runtime.exs runs at boot, so it can read environment variables on the target server.
  2. 2. How do you run migrations in a release that has no Mix?

    The generated MyApp.Release module wraps Ecto.Migrator so it works without Mix.
  3. 3. What does mix assets.deploy do?

    Digested file names let browsers cache assets for a long time safely.
  4. 4. Why do two nodes behind a balancer need clustering for Presence to be accurate?

    Without a cluster, each node only knows about its own connections.

Summary

  • Compile-time config shapes the build; runtime.exs reads the environment when the release boots.
  • mix assets.deploy plus mix release produces a self-contained artifact; mix phx.gen.release adds helpers and a Dockerfile.
  • Run migrations through a release module, and keep them backward compatible.
  • Add health and readiness endpoints, and expect LiveView clients to reconnect during deploys.
  • Cluster nodes when you need PubSub or Presence across servers, and protect the Erlang cookie.

Next: Telemetry and Observability