How to start and stop Elixir application
So one of the challenges I faced moving to the FreeBSD was that for the services I wanted have, I had to come up with a kill script for shutting down or restarting them.
The challenge is especially hard, since the PID of the Elixir applications multiplies. And you have to kill them by hand. And because of fault-tolerant nature of Elixir, it kind of feels like killing a hydra:
Cut off one head, two more shall take its place.
So what can one do?
Just create a release, and the executable contains start
stop
restart
and a bunch of more useful commands1.
So build it like this:
mix release
and for example if the application name is blog
and it is made using phoenix, you can do this:
PHX_SERVER='1' MIX_ENV='prod' _build/prod/rel/blog/bin/blog start
for a service on FreeBSD I settled on this script for my blog:
#!/bin/sh
#
# PROVIDE: blog
# REQUIRE: daemon
# BEFORE:
# KEYWORD: shutdown
#
. /etc/rc.subr
name="blog"
desc="blog - imadethissite.com"
rcvar="blog_enable"
project_dir="/home/prma/blog"
mix_exec="/usr/local/bin/mix"
daemon_exec="/usr/sbin/daemon"
mix_opts="phx.server"
secret_key_base="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
pid_file="/var/run/${name}.pid"
daemon_user="[your_user_name]"
server_port=4001
log_file="/var/log/${name}.log"
load_rc_config "$name" :"${blog_enable="NO"}"
start_cmd="blog_start"
stop_cmd="blog_stop"
compiled_path="_build/prod/rel/blog/bin/blog"
PATH=$PATH:/usr/local/lib/erlang27/bin/erl
blog_start() {
cd ${project_dir} || exit
echo "[BLOG] Starting BLOG at: http://localhost:${server_port}"
su - ${daemon_user} -c "cd ${project_dir} && PORT=${server_port} PHX_SERVER='1' MIX_ENV='prod' SECRET_KEY_BASE=${secret_key_base} $compiled_path start" >"${log_file}" 2>&1 &
echo "[BLOG] started!"
}
blog_stop() {
cd ${project_dir} || exit
echo "[BLOG] Stopping BLOG"
$compiled_path stop
echo "[BLOG] Stopped"
}
run_rc_command "$1"
-
shell
,eval
are arguably more amazing. But thestart
andstop
was the remedies that I could hardly find in the internet. ↩