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:

Here's an example Dockerfile:

FROM node:10-alpine

WORKDIR /opt/app

ENV PORT=80

# Globally installed NPMs:
RUN npm install -g pm2

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

# install packages
RUN echo 'npm install --production' >> /boot.sh

# logs by default are in logs
RUN mkdir -p logs

# npm start, make sure to have a start attribute in "scripts" in package.json
CMD sh /boot.sh && pm2-runtime --max-memory-restart=100M --output logs/out.log --error logs/error.log start npm -- start

This setting will allow to limit the maximum memory usage to 100 MB.