Clustering

Clustering Nodes

We use libcluster to manage node clustering. For more information, see libcluster’s documentation.

To install libcluster, add this to the deps list in mix.exs

{:libcluster, "~> 3.2"}

Next, add the following to the existing start function in your application.ex file. Remember to replace GigalixirGettingStarted with your application name.

def start(_type, _args) do
  topologies = Application.get_env(:libcluster, :topologies) || []

  children = [
    {Cluster.Supervisor, [topologies, [name: GigalixirGettingStarted.ClusterSupervisor]]},
    ... # other children
  ]
  ...
end

Your app configuration needs to have something like this in it. For a full example, see gigalixir-getting-started’s prod.exs file.

...
config :libcluster,
  topologies: [
    k8s_example: [
      strategy: Cluster.Strategy.Kubernetes,
      config: [
        # For Elixir Releases, use System.get_env instead of the distillery env vars below.
        kubernetes_selector: "${LIBCLUSTER_KUBERNETES_SELECTOR}",
        kubernetes_node_basename: "${LIBCLUSTER_KUBERNETES_NODE_BASENAME}"]]]
...

Gigalixir handles permissions so that you have access to Kubernetes endpoints and we automatically set your node name and erlang cookie so that your nodes can reach each other. We don’t firewall each container from each other like Heroku does. We also automatically set the environment variables LIBCLUSTER_KUBERNETES_SELECTOR, LIBCLUSTER_KUBERNETES_NODE_BASENAME, APP_NAME, and MY_POD_IP for you. See gigalixir-run for more details.

How to Set Up Distributed Phoenix Channels

If you have successfully clustered your nodes, then distributed Phoenix channels just work out of the box. No need to follow any of the steps described in Running Elixir and Phoenix projects on a cluster of nodes. See more information on how to cluster your nodes.