Set a maximum memory limit using pm2

Perhaps your instance has crashed (for example, getting the unreachable 502 status code) due to a lack of memory. Node.js applications frequently tend to have memory leaks, and so over time it can reach the amount of memory, which will crash the Node.js process. To overcome this issue, you can set a max memory limit using pm2, where it will automatically restart your instance when the limit you set is reached.

In your Dockerfile, make sure to add pm2 globally with:

RUN npm install -g pm2

Then to start it, just put the following at the end of your Dockerfile:

# npm start, make sure to have a start attribute in "scripts" in package.json
RUN echo 'pm2 --max-memory-restart=50M --output logs/out.log --error logs/error.log start npm -- start' >> /usr/bin/start.sh

# make sure it always wait
RUN echo 'sh' >> /usr/bin/start.sh

That is setting a max memory limit of 50 MB.

Here's an example Dockerfile:

FROM node:10-alpine

WORKDIR /opt/app

ENV PORT=80

RUN echo 'set -e' > /usr/bin/start.sh # this is the script which is run on start

RUN npm install -g pm2

RUN echo 'npm install --production' >> /usr/bin/start.sh

# npm start, make sure to have a start attribute in "scripts" in package.json
RUN echo 'pm2 --max-memory-restart=50M --output logs/out.log --error logs/error.log start npm -- start' >> /usr/bin/start.sh

# make sure it always wait
RUN echo 'sh' >> /usr/bin/start.sh