nodejs out of memory

Just some interesting code to remember

The Issue

When building an angular application with aws codebuild, i often get the folling error message and node.js runs out of stack memory:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed — process out of memory

This error occurs when the memory allocated for the execution application is less than the required memory when run application.

My Solution

By default the memory limit in Node.js is 512 mb, to solve this issue you need to increasing the memory limit use command —- max-old-space-size . It can be avoid the memory limit issue.

node --max-old-space-size=1024 index.js #increase to 1gb
node --max-old-space-size=2048 index.js #increase to 2gb
node --max-old-space-size=3072 index.js #increase to 3gb
node --max-old-space-size=4096 index.js #increase to 4gb
node --max-old-space-size=5120 index.js #increase to 5gb
node --max-old-space-size=6144 index.js #increase to 6gb
node --max-old-space-size=7168 index.js #increase to 7gb
node --max-old-space-size=8192 index.js #increase to 8gb

Alternatively this can be achived by setting an environment variable NODE_OPTIONS. This can be helpful when using angular cli where is is not that easy to extend the node command.

NODE_OPTIONS="--max-old-space-size=1024" ng build #increase to 1gb
NODE_OPTIONS="--max-old-space-size=2048" ng build #increase to 2gb
NODE_OPTIONS="--max-old-space-size=3072" ng build #increase to 3gb
NODE_OPTIONS="--max-old-space-size=4096" ng build #increase to 4gb
NODE_OPTIONS="--max-old-space-size=5120" ng build #increase to 5gb
NODE_OPTIONS="--max-old-space-size=6144" ng build #increase to 6gb
NODE_OPTIONS="--max-old-space-size=7168" ng build #increase to 7gb
NODE_OPTIONS="--max-old-space-size=8192" ng build #increase to 8gb

I use aws codebuild with cloudformation as a part of a codepipeline. This environment variable can be also set via cloudformation template:

...
"CodeBuild": {
  "Type": "AWS::CodeBuild::Project",
  "Properties": {
    "Name": { "Fn::Join": [ "-", [ {"Ref": "Prefix"}, "codebuild" ] ] },
    "Artifacts": { "Type": "CODEPIPELINE" },
    "Environment": {
      "ComputeType": "BUILD_GENERAL1_MEDIUM",
      "Image": "aws/codebuild/nodejs:8.11.0",
      "Type": "LINUX_CONTAINER",
      "EnvironmentVariables": [
          {"Name": "NODE_OPTIONS", "Value": "--max-old-space-size=2048"}
      ]
    },
    "ServiceRole": { "Fn::GetAtt": [ "CodebuildRole", "Arn" ] },
    "Source": {
        "Type": "CODEPIPELINE"
    },
    "TimeoutInMinutes": 15
  }
},
...

Read More

comments powered by Disqus