phoenix API服務發佈

概述

Elixir 的 Phoenix 框架對於開發 Web 應用很是方便,不只有 RoR 的便利,還有 Erlang 的性能和高併發優點。 可是應用的發佈涉及到 Erlang 和 Elixir 環境,部署不是那麼方便,特別是不少 package 須要訪問國外的服務器。html

所以,若是能像 golang 那樣,把整個應用打包成一個可執行的二進制,部署時會方便不少。 打包後不只包含應用引用的 packages,也包含 erlang 的運行環境。前端

使用 distillery 就能夠完成需求。 這裏打包的是 API 服務,也就是不包含前端的部分。git

distillery 打包

distillery 提供豐富了 API,除了打包,還有升級/降級,代碼熱替換等功能,這裏咱們只介紹打包的功能。github

建立示例工程

$ mix phx.new hello --no-brunch --no-ecto

只是實驗 phoenix 工程的打包功能,因此這裏不安裝前端的依賴,也不安裝數據庫相關依賴。golang

建立一個簡單的 api lib/hello_web/router.exweb

scope "/api", HelloWeb do
  pipe_through(:api)

  get("/", PageController, :api)
end

lib/hello_web/controllers/page_controller.ex數據庫

def api(conn, _params) do
  json(conn, %{result: "success"})
end

安裝 distillery

mix.exs 中的 deps 中添加:json

defp deps do
  [
    ...
    {:distillery, "~> 1.5", runtime: false}
  ]
end

而後在 hello 工程目錄下執行:api

mix deps.get

執行成功的話,在命令行界面上能夠看到安裝了 distillery 依賴。bash

配置 distillery 相關

首先,生成配置文件

mix release.init

這個命令生成的 rel/config.exs 沒有什麼要修改的。

修改 config/prod.exs

config :hello, HelloWeb.Endpoint,
  server: true,
  http: [port: 4001],
  url: [host: "localhost", port: 4001]

這裏寫死了 port,也能夠改爲從環境變量中讀取。

發佈工程

MIX_ENV=prod mix release

編譯成功後,在 _build/prod/rel/hello/releases/ 文件夾下生成一個 hello.tar.gz 包,這個包就能夠直接部署在其餘機器上。 若是默認配置,version 就是 0.0.1

部署運行

將生成的 hello.tar.gz 放到其餘機器也能夠直接運行,不用安裝 erlang 和 elixir 環境。

cd /home
mkdir hello
tar zxvf hello.tar.gz -C hello
cd hello
./bin/hello foreground

總結

distillery 的功能遠不止此,更多的功能能夠參考:https://hexdocs.pm/distillery/getting-started.html

相關文章
相關標籤/搜索