phoenix-ops
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePhoenix Operations and Deployment (Elixir/BEAM)
Phoenix运维与部署(Elixir/BEAM)
Production-ready Phoenix apps rely on releases, runtime configuration, telemetry, clustering, and secure endpoints. The BEAM enables rolling restarts and supervision resilience when configured correctly.
可用于生产环境的Phoenix应用依赖版本发布、运行时配置、可观测性、集群和安全端点。配置正确的情况下,BEAM支持滚动重启和监督机制带来的高可用性。
Releases and Runtime Config
版本发布与运行时配置
bash
MIX_ENV=prod PHX_SERVER=true mix assets.deploy
MIX_ENV=prod mix release
_build/prod/rel/my_app/bin/my_app eval "IO.puts(:os.type())"
_build/prod/rel/my_app/bin/my_app startconfig/runtime.exselixir
config :my_app, MyApp.Repo,
url: System.fetch_env!("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE", "10")),
ssl: true
config :my_app, MyAppWeb.Endpoint,
url: [host: System.fetch_env!("PHX_HOST"), port: 443, scheme: "https"],
http: [ip: {0,0,0,0}, port: String.to_integer(System.get_env("PORT", "4000"))],
secret_key_base: System.fetch_env!("SECRET_KEY_BASE"),
server: trueSecrets
- Prefer env vars or secret stores (AWS/GCP KMS, Vault); avoid embedding in configs.
- Generate with
SECRET_KEY_BASE.mix phx.gen.secret
bash
MIX_ENV=prod PHX_SERVER=true mix assets.deploy
MIX_ENV=prod mix release
_build/prod/rel/my_app/bin/my_app eval "IO.puts(:os.type())"
_build/prod/rel/my_app/bin/my_app startconfig/runtime.exselixir
config :my_app, MyApp.Repo,
url: System.fetch_env!("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE", "10")),
ssl: true
config :my_app, MyAppWeb.Endpoint,
url: [host: System.fetch_env!("PHX_HOST"), port: 443, scheme: "https"],
http: [ip: {0,0,0,0}, port: String.to_integer(System.get_env("PORT", "4000"))],
secret_key_base: System.fetch_env!("SECRET_KEY_BASE"),
server: true密钥管理
- 优先使用环境变量或密钥存储服务(AWS/GCP KMS、Vault);避免直接嵌入到配置文件中。
- 使用生成
mix phx.gen.secret。SECRET_KEY_BASE
Clustering and PubSub/Presence
集群与PubSub/Presence
Add for automatic node discovery:
libclusterelixir
undefined添加实现节点自动发现:
libclusterelixir
undefinedmix.exs deps
mix.exs 依赖项
{:libcluster, "> 3.3"},
{:phoenix_pubsub, "> 2.1"},
{:libcluster, "> 3.3"},
{:phoenix_pubsub, "> 2.1"},
application.ex
application.ex
topologies = [
dns_poll: [
strategy: Cluster.Strategy.DNSPoll,
config: [poll_interval: 5_000, query: "my-app.internal"],
connect: {:net_adm, :ping}
]
]
children = [
{Cluster.Supervisor, [topologies, [name: MyApp.ClusterSupervisor]]},
{Phoenix.PubSub, name: MyApp.PubSub},
MyAppWeb.Endpoint
]
**Guidelines**
- Share `secret_key_base` across nodes for consistent session signing.
- Use distributed PubSub for Presence; ensure node connectivity before enabling Presence-heavy features.
- For blue/green, keep cookies compatible between versions.拓扑配置 = [
dns_poll: [
strategy: Cluster.Strategy.DNSPoll,
config: [poll_interval: 5_000, query: "my-app.internal"],
connect: {:net_adm, :ping}
]
]
子进程列表 = [
{Cluster.Supervisor, [topologies, [name: MyApp.ClusterSupervisor]]},
{Phoenix.PubSub, name: MyApp.PubSub},
MyAppWeb.Endpoint
]
**规范**
- 所有节点共享`secret_key_base`以保证会话签名一致性。
- Presence功能使用分布式PubSub;在启用重度依赖Presence的功能前先确保节点连通性。
- 蓝绿部署时,不同版本之间的cookie要保持兼容。Telemetry, Logging, and Metrics
可观测性、日志与指标
- Install and
opentelemetry_phoenixfor traces/metrics.opentelemetry_ecto - Add and
Plug.Telemetryor structured logging.LoggerJSON - Export metrics (Prometheus/OpenTelemetry) via for VM stats (reductions, memory, schedulers).
:telemetry_poller - Set in prod; use
LOGGER_LEVEL=infoonly for troubleshooting.:debug
- 安装和
opentelemetry_phoenix采集链路追踪与指标数据。opentelemetry_ecto - 接入和
Plug.Telemetry实现结构化日志。LoggerJSON - 通过导出指标(Prometheus/OpenTelemetry),采集虚拟机统计数据(规约数、内存、调度器)。
:telemetry_poller - 生产环境设置;仅在排查问题时使用
LOGGER_LEVEL=info级别。:debug
HTTP and Network Hardening
HTTP与网络安全加固
- Enforce HTTPS (), HSTS, secure cookies (
force_ssl,same_site), and propersecure.content_security_policy - CORS: configure for API origins.
cors_plug - Rate limiting: apply plugs (ETS/Cachex token bucket) or edge (NGINX/Cloudflare).
- Uploads: prefer presigned URLs; limit request body size (,
:max_request_line_length).:max_header_value_length
- 强制HTTPS()、HSTS、安全Cookie(
force_ssl、same_site)以及合理的secure配置。content_security_policy - CORS:通过配置允许的API来源。
cors_plug - 限流:在应用层使用插件(ETS/Cachex令牌桶)或在边缘层配置(NGINX/Cloudflare)实现。
- 文件上传:优先使用预签名URL;限制请求体大小(、
:max_request_line_length)。:max_header_value_length
Assets and Static Delivery
静态资源与交付
- runs npm/tailwind/esbuild and digests assets.
mix assets.deploy - Serve static files via CDN/reverse proxy; ensure headers set in Endpoint.
cache-control - Disable unused watchers in production to trim image size.
- 会执行npm/tailwind/esbuild构建并为资源添加哈希戳。
mix assets.deploy - 通过CDN/反向代理提供静态资源服务;确保在Endpoint中配置了正确的响应头。
cache-control - 生产环境禁用未使用的监听程序以减小镜像体积。
Background Jobs
后台任务
- Oban recommended for retries/backoff, scheduled jobs, and isolation; supervise in .
application.ex - Configure queues via runtime env; monitor with Oban Web/Pro or telemetry.
- For CPU-heavy tasks, consider pooling or external workers to avoid blocking schedulers.
- 推荐使用Oban实现重试/退避、定时任务和隔离执行;在中配置监督。
application.ex - 通过运行时环境变量配置队列;使用Oban Web/Pro或可观测性工具监控队列状态。
- 对于CPU密集型任务,考虑使用池化或外部Worker避免阻塞调度器。
Deployment Patterns
部署模式
- Containers: multi-stage builds; run ,
mix deps.get --only prod,mix compile, thenmix assets.deploy.mix release - Systemd: run release binary as service with secrets; add
Environment=.Restart=on-failure - Fly/Gigalixir/Render: supply env vars, attach Postgres/Redis, open long-lived WebSocket ports.
- Blue/green or canary: keep DB migrations compatible; deploy code first, then run migrations; keep feature flags for schema changes.
- 容器部署:使用多阶段构建;依次执行、
mix deps.get --only prod、mix compile,最后执行mix assets.deploy。mix release - Systemd部署:将发布的二进制文件作为服务运行,通过配置密钥;添加
Environment=配置。Restart=on-failure - Fly/Gigalixir/Render平台部署:配置环境变量、绑定Postgres/Redis服务、开放长连接WebSocket端口。
- 蓝绿或金丝雀部署:保证数据库迁移的兼容性;先部署代码,再执行迁移;为schema变更添加功能开关。
Observability and Health
可观测性与健康检查
- Add and
/healthendpoints (Repo check + PubSub/Presence check)./ready - Export VM metrics: run for scheduler utilization and memory.
:telemetry_poller - Alert on error rates, DB timeouts, queue depths, and VM memory.
- 添加和
/health端点(检查数据库连接 + PubSub/Presence状态)。/ready - 导出虚拟机指标:运行采集调度器利用率和内存数据。
:telemetry_poller - 针对错误率、数据库超时、队列深度、虚拟机内存配置告警。
Common Pitfalls
常见陷阱
- Building releases without (endpoint won’t start).
PHX_SERVER=true - Missing runtime config in ; relying on compile-time config for secrets.
config/runtime.exs - No cluster discovery configured → Presence inconsistencies across nodes.
- Leaving default or per-node keys → invalid sessions after deploy.
secret_key_base - Large assets without digests/CDN → slow cold loads.
- 构建版本时未设置(端点不会启动)。
PHX_SERVER=true - 中缺少运行时配置;依赖编译时配置存储密钥。
config/runtime.exs - 未配置集群发现 → 不同节点间的Presence数据不一致。
- 保留默认的或每个节点使用独立的密钥 → 部署后会话失效。
secret_key_base - 大型静态资源未添加哈希戳或未接入CDN → 冷加载速度慢。