Bonus – starting a detached HTTP server
Running a detached server is quite useful, especially in scenarios where you need to run a detached console for debugging purposes while the app is running. We can confirm this by running an iex console with the following command:
$ iex -S mix [info] Started a webserver on port 4001
Running the iex command should print the preceding info log. Even though you started an iex shell, you won’t have access to the shell or any other process in the supervision tree. In order to fix this, we can use Task.start_link/3 and run the HTTP server process as a Task.
Let’s update the child_spec/1 function in the HTTP server to start a Task:
lib/goldcrest_http_server.ex
defmodule Goldcrest.HTTPServer do
# ..
def child_spec(init_args) do
%{
id: __MODULE__,
start: {
...