Beginners guide to Ethereum (2) — run multiple nodes on a private network in 5 lines

Overview

This tutorial serves as a guide to let beginners quick start by learning from a working example. It’s also my personal learning notes:)

In the following tutorial, we will setup and connect two nodes on the same private network with the least lines of code.

Operating system: macOS

Things to know before we go…

The simplest way to setup a private network is to

  1. determine the data directory for storing the blockchain data
  2. choose a networkid (the default value 1 is the main network)

To get nodes running on a single machine, we need to specify different ports for each of them.

Start coding!

  1. Use geth to open a node on a specified network and open the geth console. Here we set our network id to 123.

In the first teminal,

geth --datadir data1 --port 30301 --networkid 123 --dev console 
// The --dev flag is to use the default genesis file settings, you can also create your own genesis file and replace this flag with init "path_of_your_genesis.json"

In the second terminal,

geth --datadir data2 --port 30302 --networkid 123 --dev console 
//remember to run your second node on a different port!

You don’t need to create folder data1 and data2 since geth will create it for you if the folder does not exist.

2. Now, your two nodes should be running on the same network. Next, find the enode url of one of your nodes.

Enode url is like a unique id for nodes to communicate with each other

In the first terminal, (now it should be in the geth console)

admin.nodeInfo.enode 

The output should be like the output should be like enode://b7cfadc86549c931be4e0ffca03299053b31dd40503313e05cbdc855399fca225623dd7e2e262a1f45e01137345641c4d90b88080cd678a03867f53bca890315@[::]:30302

Where [::] is equivalent to 127.0.0.1 (localhost) and 30302 is the port your node is running on.

3. Connecting the nodes

Before connecting, there should be no peer right now

web3.net.peerCount //output 0

In the second terminal,

admin.addPeer(“enode_url_u_just_get_from_the_first_terminal”)

And then check if the node is successfully added

web3.net.peerCount //output 1

Wrap up

Now you have two connected nodes running on your network (id 123). You can use this to increase your mining power or simply emulates the main network which contains multiple nodes. (To start mining, remember to create your first account by personal.newAccount('') before miner.start())

Reference

Thank you for your reading! I’m open to any suggestion :)