Install Elasticsearch on CentOS with small amount of memory and deal with "memory allocation" error

Prerequisites

Elasticsearch is built using Java, and requires at least Java 8 in order to run.

To check your Java version, use the following command:

java -version

You should get something like this:

java version "1.8.0_45"  
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)  
Java HotSpot(TM) Server VM (build 25.45-b02, mixed mode)

Download latest Elasticsearch

To download the latest version of Elasticsearch (currently 5.0.1) visit this page and copy to clipboard the link address for the rpm file.

Then use wget command to download the package:

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.0.1.rpm

Install Elasticseach

Now, to install the downloaded rpm package use the following command:

sudo rpm -ivh elasticsearch-5.0.1.rpm

Start the service (and get the "memory allocation" error)

To manually start Elasticsearch use the following command:

sudo service elasticsearch start

If the result looks like this...

Starting elasticsearch: [  OK  ]  

...that's fine. But, if the result reports:

error='Cannot allocate memory' (errno=12)  
...
There is insufficient memory for the Java Runtime Environment to continue.  

the Java heap size (-Xmx/-Xms) must be decreased.

How much? You can set the value following some simple rules that you can find in Elasticsearch's guides regarding JVM heap size. Generally, a good start is setting the value to half of the free physical memory of the system.

How to set the value? By editing the jvm.options file which is normally located in the /etc/elasticsearch/ directory:

Replace the default values (2Gb):

-Xms2g
-Xmx2g

with (for 512Mb):

-Xms512m
-Xmx512m

Then, try to start the service again.

Testing

Easily, you can test the service is working using the following command:

curl -X GET 'http://localhost:9200'

The response should look like this:

{
  "name" : "xxxxxxx",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "xxxxxxx",
  "version" : {
    "number" : "x.x.x",
    "build_hash" : "xxxxxxx",
    "build_date" : "xxxxxxx",
    "build_snapshot" : false,
    "lucene_version" : "x.x.x"
  },
  "tagline" : "You Know, for Search"
}

Additional resources

Elasticsearch configuration