elixir mix开发入门
备注:
简单使用mix 进行项目的生成,同时添加docker 构建支持
1. 生成项目
mix new mydemoproject
输出信息如下:
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/mydemoproject.ex
* creating test
* creating test/test_helper.exs
* creating test/mydemoproject_test.exs
Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:
cd mydemoproject
mix test
Run "mix help" for more commands.
项目结构如下:
├── README.md
├── config
│ └── config.exs
├── lib
│ └── mydemoproject.ex
├── mix.exs
└── test
├── mydemoproject_test.exs
└── test_helper.exs
2. 项目结构说明
a. config
主要是对于不同环境的变量配置
b. lib
主要是我们自己的业务代码放置
c. mix.exs
应用运行的一些配置,包括依赖包,构建,运行的说明,后面会有doc 以及main 入口的参考例子
d. test
单元测试的代码
3. 添加一些功能
备注: 项目运行结构
├── Dockerfile
├── README.md
├── config
│ └── config.exs
├── lib
│ ├── mydemoproject
│ │ └── run.ex
│ └── mydemoproject.ex
├── mix.exs
└── test
├── mydemoproject_test.exs
└── test_helper.exs
a. docs (项目帮助文档)
添加依赖包 mix.exs
defp deps do
[
{:ex_doc, "~> 0.14", only: :dev}
]
end
添加文档的描述 mix.exs
def project do
[
app: :userlogin,
version: "0.1.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package(),
docs: [extras: ["README.md"], # 文档的起始地址
main: "readme"]
]
end
defp package do
%{maintainers: ["dalongrong"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/rongfengliang/elixir-dockerbuild"}}
end
b. 项目启动入口 mix.exs
# 入口声明
def project do
[
app: :mydemoproject,
version: "0.1.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
escript: escriptconfig(),
package: package(),
docs: [extras: ["README.md"], # 文档的起始地址
main: "readme"],
deps: deps()
]
end
# 入口定义
defp escriptconfig do
[ main_module: Mydemoproject.Start]
end
lib/mydemoproject/run.ex
defmodule Mydemoproject.Start do
def main(argv) do
IO.puts "hello world"
end
end
c. docker 构建支持(使用的docker stage 构建,需要docker ce 17或者最新版本)
# build stage
FROM elixir:1.6-alpine AS build-env
WORKDIR /app
COPY * /app/
RUN cd /app \
&& mix local.hex --force \
&& mix local.rebar --force \
&& mix deps.get \
&& mix deps.compile \
&& cp mydemoproject /tmp/
FROM erlang:20-alpine
WORKDIR /app
COPY --from=build-env /tmp/mydemoproject /app/mydemoproject
CMD ["./mydemoproject"]
4. 项目构建
a. 依赖下载
mix.deps.get
b. 构建
mix escript.build
c. 项目文档
mix docs
d. docker 构建
docker build -t mydemoproject .
e. 运行
local
./mydemoproject
docker
docker run -it mydemoproject ./mydemoproject
5. 参考资料
https://github.com/rongfengliang/elixir-dockerbuild