/elixir-phoenix-guide:deployment-gotchasfrom elixir-phoenix-guide
Covers common Phoenix deployment pitfalls: release generation, runtime vs compile-time config, migrations, Dockerfile build order, health checks, and SSL. For Elixir/Phoenix developers preparing releases.
Ships in elixir-phoenix-guide. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14 — October 2026
Not a deployment guide. These are the things that break first Phoenix deploys, each tied to a real incident pattern.
mix phx.gen.release --docker — it generates MyApp.Release, bin/migrate, bin/server and a Dockerfile in the right build order; don't hand-write themruntime.exs; compile-time settings stay in config/prod.exs — force_ssl and anything read with Application.compile_env can't be changed at bootbin/migrate before the new code takes traffic, and keep them backward-compatible — during a rolling deploy the old version runs against the new schema (expand, then contract in a later deploy)bin/server (sets PHX_SERVER=true) and set PHX_HOST — runtime.exs enables the server only when PHX_SERVER is set; a wrong host breaks generated URLs and the websocket check_origindeps.compile → compile → assets.deploy → release — colocated hooks are extracted during mix compile, so assets built before compiling miss themruntime.exs and fail at boot if missinginspect(reason) leaks hostnames)force_ssl with rewrite_on: [:x_forwarded_proto], enable database SSL, keep check_originconfig :logger, level: :info in production — :debug logs query parameters, which contain user datamix phx.gen.release --docker
It creates:
lib/my_app/release.ex — migrate/0 and rollback/2, runnable without Mixrel/overlays/bin/migrate — runs ./my_app eval MyApp.Release.migraterel/overlays/bin/server — runs PHX_SERVER=true exec ./my_app startDockerfile and .dockerignore — a multi-stage build pinned to your Elixir/OTP versionsHand-written release.ex files often use Application.load(@app). That returns {:error, {:already_loaded, _}} when the app is already loaded. The generator uses the idempotent Application.ensure_loaded/1:
# lib/my_app/release.ex (generated)
defp load_app do
# Many platforms require SSL when connecting to the database
Application.ensure_all_started(:ssl)
Application.ensure_loaded(@app)
end
The incident: DATABASE_URL is set correctly in production, but the release connects to the build machine's database, or to none.
Why: config.exs and prod.exs are evaluated when you build the release and baked into it. runtime.exs is evaluated at boot.
# config/prod.exs — runs on the build machine
config :my_app, MyApp.Repo, url: System.get_env("DATABASE_URL")
# config/runtime.exs
if config_env() == :prod do
config :my_app, MyApp.Repo,
url: System.fetch_env!("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
end
The reverse mistake: some settings are read at compile time with Application.compile_env/3 and can't be changed at boot. Examples are the endpoint's force_ssl, code_reloader and debug_errors, and the generated :dev_routes. Set them in config.exs/prod.exs. If runtime.exs sets one to a different value, the release refuses to boot ("the application :my_app has a different value set for key ... during runtime compared to compile time").
The incident: a deploy renames users.name to users.full_name. For the two minutes when old and new instances both serve traffic, every request on the old instances 500s.
# In production — no Mix in a release
bin/migrate
# or: bin/my_app eval "MyApp.Release.migrate()"
Run it as a pre-deploy step (a release command, init container or job) before new instances start. Then the old version briefly runs against the new schema, so every migration must be safe for the code that's already deployed:
| Change | Safe sequence |
|---|---|
| Add a column | Add it as nullable or with a default → deploy the code that writes it → backfill → add NOT NULL later |
| Rename a column | Add the new column → write both → backfill → read the new one → drop the old one in a later deploy |
| Drop a column | Stop reading it (remove it from the schema) → deploy → drop it in the next deploy |
| Add an index on a big table | create index(..., concurrently: true) with @disable_ddl_transaction true and @disable_migration_lock true |
The exact migration code for each row (including NOT NULL without a full-table scan and lock_timeout) is in the ecto-migrations-safety skill.
Don't run migrations from Application.start/2. Every node would race to run them on boot.
The incident: the release starts and the health check passes, but nothing listens on the port. Or emails link to https://example.com.
The generated runtime.exs already does the right thing:
# config/runtime.exs (generated)
if System.get_env("PHX_SERVER") do
config :my_app, MyAppWeb.Endpoint, server: true
end
if config_env() == :prod do
host = System.get_env("PHX_HOST") || "example.com"
config :my_app, MyAppWeb.Endpoint,
url: [host: host, port: 443, scheme: "https"],
# IPv6 dual-stack: accepts IPv4 and IPv6 on all interfaces
http: [ip: {0, 0, 0, 0, 0, 0, 0, 0}]
end
bin/server, which sets PHX_SERVER=true. bin/my_app start alone boots the app without the HTTP listener. Keep the conditional rather than an unconditional server: true, so you can still boot a node without the listener (a worker-only node, or a bin/my_app start_iex maintenance console).PHX_HOST. The fallback "example.com" produces wrong links and makes check_origin reject every websocket connection.ECTO_IPV6=true makes the Repo connect over IPv6 (socket_options: [:inet6]). Fly.io's private network, for example, is IPv6-only.DNS_CLUSTER_QUERY feeds the generated {DNSCluster, query: ...} child, which connects nodes for PubSub and Presence across instances. Without it each node is alone and broadcasts don't cross instances.The incident: CSS and JS 404, or LiveView colocated hooks are missing from app.js.
The generated Dockerfile builds in this order. Keep it:
COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV
RUN mkdir config
COPY config/config.exs config/${MIX_ENV}.exs config/
RUN mix deps.compile
RUN mix assets.setup
COPY priv priv
COPY lib lib
# Compile first: colocated hooks/JS are extracted at compile time
RUN mix compile
COPY assets assets
RUN mix assets.deploy
# runtime.exs last: changing it doesn't invalidate the compile layers
COPY config/runtime.exs config/
COPY rel rel
RUN mix release
mix assets.deploy runs tailwind and esbuild with --minify, then phx.digest, which writes the priv/static/cache_manifest.json that prod.exs points the endpoint at. Compiling first matters for CSS too: app.css imports the phoenix-colocated CSS that mix compile writes (see the phoenix-tailwind-daisyui skill).
# config/prod.exs — in git history forever, baked into the release
config :my_app, MyAppWeb.Endpoint, secret_key_base: "actual_secret_key_here"
# config/runtime.exs
if config_env() == :prod do
config :my_app, MyAppWeb.Endpoint, secret_key_base: System.fetch_env!("SECRET_KEY_BASE")
end
fetch_env! crashes at boot with a clear message. get_env returns nil and fails later in a confusing place. Generate a value with mix phx.gen.secret.
config/prod.exs has force_ssl: [rewrite_on: [:x_forwarded_proto], exclude: [hosts: ["localhost", "127.0.0.1"]]]. rewrite_on makes the app trust the proxy's x-forwarded-proto; without it every request looks like HTTP and you get a redirect loop. If the load balancer probes over plain HTTP, add the health paths: exclude: [paths: ["/health/live", "/health/ready"], hosts: [...]].runtime.exs leaves # ssl: true commented out. With Postgrex 0.21+, ssl: true verifies the server certificate against the OS CA store (:public_key.cacerts_get()). If you pass a keyword list instead (ssl: [...]), add cacerts: :public_key.cacerts_get() (or cacertfile: for a provider's private CA) yourself: the list form doesn't add CA certificates.check_origin on; it compares the Origin header with url: [host: ...] (so PHX_HOST must be right), and several domains are listed explicitly. See the phoenix-channels-essentials skill.The incident: a database blip makes every instance fail its health check. The orchestrator restarts the whole fleet, and the reconnect storm makes the outage longer.
Keep two checks with different jobs. Liveness ("is this BEAM alive?") must not touch the database. Failing it restarts the instance. Readiness ("can this instance serve?") queries the database. Failing it takes the instance out of rotation without restarting it.
# router.ex — outside :browser (no session/CSRF needed)
scope "/health", MyAppWeb do
pipe_through :api
get "/live", HealthController, :live
get "/ready", HealthController, :ready
end
defmodule MyAppWeb.HealthController do
use MyAppWeb, :controller
alias Ecto.Adapters.SQL
require Logger
def live(conn, _params), do: send_resp(conn, 200, "ok")
def ready(conn, _params) do
case SQL.query(MyApp.Repo, "SELECT 1", [], timeout: 1_000) do
{:ok, _} ->
json(conn, %{status: "ok"})
{:error, reason} ->
# Details go to the log, never to the (often public) response
Logger.error("Readiness check failed: #{inspect(reason)}")
conn
|> put_status(:service_unavailable)
|> json(%{status: "unavailable"})
end
end
end
Point the liveness probe at /health/live and the readiness probe (or the load balancer's target health check) at /health/ready.
The incident: log storage costs spike, and the logs contain full SQL parameters: emails and addresses.
The generated config/prod.exs sets config :logger, level: :info. Keep it. To allow a temporary override without a rebuild:
# config/runtime.exs
if config_env() == :prod do
level =
case System.get_env("LOG_LEVEL") do
"debug" -> :debug
"warning" -> :warning
"error" -> :error
_ -> :info
end
config :logger, level: level
end
At runtime on a live node you can also call Logger.configure(level: :debug) from bin/my_app remote, then set it back.
Oban.Migrations.up/1, so bin/migrate covers them. Oban upgrades that need a new migration version go through the same path.config.exs and switch it off per node in runtime.exs with queues: false. The node starts no queues and can still insert jobs.queues: [] for this: config files deep-merge keyword lists, and [] is an empty keyword list, so [default: 10] from config.exs survives the merge. For the same reason, a queues: [...] list in runtime.exs is merged into the config.exs list, not substituted for it.# config/runtime.exs
if config_env() == :prod and System.get_env("OBAN_QUEUES") == "false" do
config :my_app, Oban, queues: false
end
See the oban-essentials skill for Oban configuration.
Platform specifics (Fly.io, Gigalixir, Render, Kubernetes manifests, CI pipelines) are covered in platform docs and the Phoenix deployment guides.
See the telemetry-essentials skill for production logging and observability.
See the security-essentials skill for secrets, HTTPS and cookie settings.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub j-morgan6/elixir-phoenix-guide --plugin elixir-phoenix-guide24 skills in this plugin
/code-qualityUse when refactoring or reviewing Elixir code quality — compiler warnings and Credo first, then the plugin's on-demand duplication and branch-complexity scans. Not for style rules while writing code (use elixir-essentials)./ecto-changeset-patternsUse when writing Ecto changeset validations beyond cast/validate_required — custom and cross-field validations (e.g. end date after start date), separate changesets per operation (registration vs update), conditional validation, field transforms, password/email rules, uniqueness checks. Not for parent/child forms or cast_assoc (use ecto-nested-associations)./ecto-essentialsUse when defining schemas, writing queries, or creating migrations — scoped context functions, Repo.transact, upserts, indexes, query composition, safe field casting. Not for multi-changeset design (ecto-changeset-patterns) or nested children (ecto-nested-associations).Other plugins' skills for the same job