How can I connect two Erlang/Elixir-nodes of two different machines via network connection?
2 Answers
You have to name your nodes and use the same cookie on both nodes.
In machine 1:
iex --name node1@machine1.com --cookie a_cookie_string
In machine 2:
iex --name node2@machine2.com --cookie a_cookie_string
Now the two machines can communicate. To test it, you can do something like this, on machine1:
iex(node1@machine1.com)1> Node.connect :"node2@machine2.com"
true
iex(node1@machine1.com)2> print_node_name = fn -> IO.puts Node.self end
#Function<erl_eval.20.80484245>
iex(node1@machine1.com)3> Node.spawn(:"node2@machine2.com", print_node_name)
node2@machine2.com
#PID<7789.49.0>
Domain names machine1.com
and machine2.com
can be changed with the ip addresses of the machines as well.

- 20,218
- 7
- 70
- 53
-
1Cool, this works! :) I already try this approach but used domains instead of ip-addresses. Thanks a lot – ChaosSteffen Jun 28 '13 at 13:53
-
2BTW: The node names can be the same before the `@` sign as long as the domain name part is different (the names must be unique in the network, so if you use IP addresses for your machines than this is the unique part). Example: `node@192.168.0.2` and `node@192.168.0.3` is working, too. (Just mentioned to maybe simplify your code related to machine/node names.) – asaaki Jul 03 '13 at 20:22
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 :"foo@192.168.0.1"
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 bar@192.168.0.2 (assuming this Node is another computer on the same local network). The code to do this, looks like Node.connect :"bar@192.168.0.2"
You can now run Node.list to see the bar@192.168.0.2
available on foo@192.168.0.1
and vice versa.
Summarising the above points, your code should look something like
On the Foo machine
Node.start :"foo@192.168.0.1" #this is the IP of the machine on which you run the code
Node.set_cookie :cookie_name
Node.connect "bar@192.168.0.2"
On the Bar machine
Node.start :"bar@192.168.0.2"
Node.set_cookie :cookie_name

- 340
- 7
- 7