Learning objectives
After reading this article you will be able to:
- Set up a production runtime.exs driven by environment variables
- Build assets, migrate the database and start with mix or a release
- Fix the most common errors of a freshly deployed Phoenix app
On this page
Phoenix runs on the BEAM, Erlang's virtual machine, and it was built for lots of simultaneous connections: Channels and LiveView keep one WebSocket open per user without breaking a sweat. Moving a project from a local mix phx.server to production, though, takes what development mode hides from you: secrets in environment variables, digested assets, the public host configured, and a server listening on the right interface.
This guide starts from a project created with mix phx.new, adjusts config/runtime.exs, shows both ways to start in production (mix or a release), and covers shutdown and common errors. For the big picture of shipping any backend, see how to host an API.
What changes between development and production?#
In production, Phoenix runs with MIX_ENV=prod and reads its configuration from config/runtime.exs, which runs at boot, after compilation. That file turns environment variables into configuration. A generated project expects these:
| Variable | What it does | Example |
|---|---|---|
MIX_ENV |
Picks the build and config environment | prod |
SECRET_KEY_BASE |
Signs and encrypts cookies and sessions | output of mix phx.gen.secret |
PHX_HOST |
Public host, used to build URLs and check WebSocket origins | myapp.example.com |
PORT |
Port the server listens on | set by the environment |
DATABASE_URL |
Ecto's database connection | ecto://USER:PASS@HOST/DATABASE |
POOL_SIZE |
How many connections Ecto opens | 10 |
PHX_SERVER |
Turns on the web server in a release | true |
Without SECRET_KEY_BASE or DATABASE_URL, the generated runtime.exs stops the boot on purpose, with a message naming the missing variable. More on this in what are environment variables.
How do you prepare runtime.exs for production?#
The generated file already reads almost everything. The setting that matters most is the listen address: the project ships with ip: {0, 0, 0, 0, 0, 0, 0, 0}, which binds to every IPv6 interface. According to the Erlang docs, on most Linux distributions that socket also accepts IPv4, but it depends on the system; with {0, 0, 0, 0}, Erlang's spelling of 0.0.0.0, you don't depend on it. Replace my_app and MyApp with your project's names:
import Config
if System.get_env("PHX_SERVER") do
config :my_app, MyAppWeb.Endpoint, server: true
end
config :my_app, MyAppWeb.Endpoint,
http: [port: String.to_integer(System.get_env("PORT", "4000"))]
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"))
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"
config :my_app, MyAppWeb.Endpoint,
url: [host: host, port: 443, scheme: "https"],
http: [ip: {0, 0, 0, 0}],
secret_key_base: secret_key_base
endurlwithport: 443andscheme: "https": Phoenix builds links and checks WebSocket origins against the public host, not the internal port. The host's proxy terminates HTTPS and forwards to the process on thePORTport.- The two
httpkeys merge: the top one sets the port in every environment, the production one adds the address. - A database that requires TLS: if the database uses its own CA, the Repo's
ssloption takes a list withcacertfilepointing at the CA certificate (pluscertfilewhen the server also requires a client certificate), as the Postgrex docs show. For certificate errors, see self signed certificate in certificate chain.
How do you build assets and run migrations?#
The sequence from the Phoenix deployment guide, running the app through Mix:
mix phx.gen.secret # copy the output into SECRET_KEY_BASE
mix deps.get --only prod
MIX_ENV=prod mix compile
MIX_ENV=prod mix assets.deploy
MIX_ENV=prod mix ecto.migrate
PORT=4001 MIX_ENV=prod mix phx.servermix assets.deploy runs Tailwind and esbuild with --minify, then phx.digest, which writes copies of the files with a hash in their names plus cache_manifest.json to priv/static. Tailwind downloads itself on first run if it isn't installed yet. Skip this step and the generated prod.exs points to a manifest that doesn't exist: the server still boots, but it logs the error below, and pages may load without CSS and without the JavaScript that connects LiveView.
[error] Could not warm up static assets: could not find static manifest at ".../priv/static/cache_manifest.json". Run "mix phx.digest" after building your static files or remove the "cache_static_manifest" configuration from your config files.Projects generated by recent Phoenix versions don't depend on Node.js. If you installed npm packages into assets/ (with npm install some-package --prefix assets), the asset management guide recommends adding "cmd --cd assets npm ci" to the assets.deploy alias in mix.exs, so the deploy installs them.
Run mix ecto.migrate on every deploy, before the new code takes traffic. Database migrations on deploy covers what to do when a migration is slow or breaks compatibility with the previous version.
Mix or a release: how do you start in production?#
There are two paths, and the choice depends on where the code compiles:
mix phx.server with MIX_ENV=prod |
Release (mix release) |
|
|---|---|---|
| Elixir and Erlang on the server | Required | Not needed if the release bundles ERTS (the default) |
| Where it compiles | On the server itself | On a machine with the server's OS and architecture |
| Web server | Always on | With PHX_SERVER=true or bin/server |
| Migrations | mix ecto.migrate |
bin/migrate |
| Fits | Environments that already ship Elixir | Slim images and VPSes without a toolchain |
To build a release:
mix phx.gen.release
MIX_ENV=prod mix assets.deploy
MIX_ENV=prod mix release
_build/prod/rel/my_app/bin/migrate
_build/prod/rel/my_app/bin/servermix phx.gen.release creates the bin/server script (which sets PHX_SERVER=true for you) and bin/migrate, plus a MyApp.Release module that runs migrations without Mix. The Mix docs warn that a release only works on a target with the same operating system, distribution and architecture as the machine that assembled it: a release built on a MacBook won't run on an Ubuntu server.
How does Phoenix shut down on SIGTERM?#
When a process is stopped (a restart, a new deploy, docker stop), the environment sends SIGTERM. The BEAM treats it as init:stop(): applications and their supervision trees stop one by one, in reverse start order. Unlike Node.js or Go, you don't have to write a handler.
For long-lived connections, the Endpoint has a socket drainer. On shutdown it tells Channels and LiveView clients to reconnect, in batches of 10,000 every 2 seconds, capped at 30 seconds in total. The LiveView JavaScript client retries on its own and finds the new instance once it's up. If the environment sends SIGKILL before that cap, lower the drainer's shutdown in your socket config. For the infrastructure side, see how to host a WebSocket server.
What are the most common errors?#
Two messages show up often in the logs. The first says the secret never reached the process, and the app won't boot:
** (RuntimeError) environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secretThe second appears when LiveView or a Channel keeps reconnecting:
Could not check origin for Phoenix.Socket transport.
Origin of the request: https://myapp.example.com| Symptom | Cause | Fix |
|---|---|---|
SECRET_KEY_BASE is missing |
The variable never reached the process | Generate a value with mix phx.gen.secret and set it in the environment, never in a committed file |
Could not check origin and LiveView reconnecting |
The host in url doesn't match the browser's domain |
Fix PHX_HOST; with more than one domain, list them in check_origin |
ERR_TOO_MANY_REDIRECTS in the browser |
force_ssl doesn't get the proxy's X-Forwarded-Proto |
Confirm the header or, if your host already redirects to HTTPS, drop force_ssl |
Could not warm up static assets and an unstyled page |
mix assets.deploy was skipped |
Run it before starting the server |
| The log shows the Endpoint up, but nothing answers from outside | An interface the proxy can't reach, or a release without PHX_SERVER |
Listen on {0, 0, 0, 0} and use bin/server or PHX_SERVER=true |
| With several instances, broadcasts or long-polling sessions get lost | The default PubSub only reaches other instances in an Erlang cluster | Clustering or an adapter such as Phoenix.PubSub.Redis; for long polling, the deployment guide also accepts sticky sessions |
The redirect case deserves a closer look. The generated prod.exs turns on force_ssl with rewrite_on: [:x_forwarded_proto]: Phoenix trusts the proxy's X-Forwarded-Proto header to know the original connection was HTTPS. If the proxy doesn't send it, every request looks like HTTP and gets redirected again. Dropping force_ssl also drops the HSTS header it adds. The mechanism is explained in ERR_TOO_MANY_REDIRECTS, and other reasons a WebSocket won't connect in WebSocket connection failed.
How to do this on Square Cloud#
On Square Cloud, the Elixir runtime runs mix deps.get on the server, and the image already ships Node.js with npm for mix assets.deploy (handy when the alias runs npm ci), with no separate build step. Upload the project with a ZIP in the dashboard, the CLI, GitHub or the VS Code extension. The squarecloud.app file is optional: the dashboard generates it on deploy. With the CLI, list _build/ and deps/ in squarecloud.ignore (.gitignore syntax) so you don't upload what was compiled or fetched on your machine, and add !mix.lock so the lockfile goes along.
In the app's environment variables, set MIX_ENV=prod, SECRET_KEY_BASE, PHX_HOST with your *.squareweb.app subdomain (or your custom domain, from the Standard plan), and DATABASE_URL. The platform sets PORT, and this guide's runtime.exs already reads it and listens on 0.0.0.0; only port 80 receives traffic, published over HTTPS. An example start command (START), to adjust to your project: mix assets.deploy && mix ecto.migrate && mix phx.server. START runs as a shell command, up to 256 characters.
The proxy doesn't cut long-lived connections, so LiveView and Channels WebSockets go through unbuffered, and the HTTP to HTTPS redirect comes from the platform. A web app uses at least 512 MB of the plan's RAM pool. If the process exits with an error, auto restart (on by default when you deploy from the dashboard) brings it back; running out of memory stops the app until you add RAM and start it again. Hobby starts at R$12.49 a month, with 1 GB. For more than one instance, load balancing (from the Standard plan) splits the same custom domain across 2 or more apps in round-robin, with no sticky sessions: give them all the same SECRET_KEY_BASE and use an adapter such as Phoenix.PubSub.Redis so broadcasts reach every one of them.
For Ecto, PostgreSQL hosting starts on the Standard plan (from R$44.99 a month), in the same datacenter as your apps. TLS is required: the Repo has to trust the CA you download from the dashboard and present the .pem certificate. Each database accepts up to 256 connections, so add up the POOL_SIZE of every app that shares a database. See the details of Elixir hosting.
API hosting
APIs in always-on containers, with no cold starts
FAQs
Do I need Node.js to deploy a Phoenix app?
Not by default: projects generated by recent Phoenix versions integrate esbuild and Tailwind and don't depend on Node.js. You only need it once you install npm packages into the assets folder.
What is PHX_SERVER for?
The generated runtime.exs reads it to turn on the web server. mix phx.server starts the server on its own; in a release you need PHX_SERVER=true or the bin/server script that mix phx.gen.release creates.
How do I generate SECRET_KEY_BASE?
Run mix phx.gen.secret and store the output in an environment variable, outside the repository. It signs and encrypts cookies and sessions, so changing it invalidates existing sessions.
Why does LiveView keep reconnecting in production?
Most of the time the host in your url config doesn't match the domain the browser uses, so the origin check rejects the WebSocket. Set PHX_HOST to the public domain and look for Could not check origin in the logs.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- CORS error (blocked by CORS policy): cause and fixA CORS error means the API did not allow your page's origin. Learn the causes, how to fix it in Express and FastAPI, and how to test the preflight with curl.