How to connect two Elixir nodes via local network?

Solution 1:

You have to name your nodes and use the same cookie on both nodes.

In machine 1:

iex --name [email protected] --cookie a_cookie_string

In machine 2:

iex --name [email protected] --cookie a_cookie_string

Now the two machines can communicate. To test it, you can do something like this, on machine1:

iex([email protected])1> Node.connect :"[email protected]"
true

iex([email protected])2> print_node_name = fn -> IO.puts Node.self end
#Function<erl_eval.20.80484245>

iex([email protected])3> Node.spawn(:"[email protected]", print_node_name)
[email protected]
#PID<7789.49.0> 

Domain names machine1.com and machine2.com can be changed with the ip addresses of the machines as well.

Solution 2:

If you are trying to connect Nodes via code: You need to turn your running code into a distributed node. To do this run Node.start(:fullNameOfServer).

Eg: if your IP is 192.168.0.1, you can have a full Node name like :"[email protected]"

Once you turn your node into a distributed node, you set the cookie: Node.set_cookie :cookie_name

Finally, you need to establish a connection with the remote Node. (You also need to Node.start and Node.set_cookie on the remote node) To do this, you need the remote node's name. Let us assume the remote node's name is [email protected] (assuming this Node is another computer on the same local network). The code to do this, looks like Node.connect :"[email protected]"

You can now run Node.list to see the [email protected] available on [email protected] and vice versa.

Summarising the above points, your code should look something like

On the Foo machine

Node.start :"[email protected]" #this is the IP of the machine on which you run the code
Node.set_cookie :cookie_name
Node.connect "[email protected]"

On the Bar machine

Node.start :"[email protected]" 
Node.set_cookie :cookie_name