DEV Community

Cover image for Deploying Multiple NodeJS Servers on a Single DigitalOcean Droplet; Managed by PM2, Without Using an ecosystem.config.js file
Chukwunazaekpere
Chukwunazaekpere

Posted on

Deploying Multiple NodeJS Servers on a Single DigitalOcean Droplet; Managed by PM2, Without Using an ecosystem.config.js file

Firtly, my servers are nginx-based and certified by certbot - let's encrypt. Hence, I'm assuming you're acquainted with this setup. Now, unto the epicenter of our problem.
A major problem using the prescribed (best-practise) procedure for deploying several NodeJS server instances on digitalOcean (referred to as DO hereafter), is that; environment variables become difficult to locate; once the server is started. This becomes a bigger trouble when there are more than one servers, to be used on a single droplet. I circumvented through this challenge, by doing the following;

a) Create various folders, on DO named w.r.t how you'd like PM2 to identify these servers; i.e. if you've got 3 servers to deploy on a single droplet, you'd say;
e.g plutonium_server, neptunium_server, promethium_server

b) clone your repo into each folder: git clone https://github.com...

c) cd into the repo; sudo nano package.json

d) in your start script, enter: "pm2 start <your start file>"
e.g: "pm2 start ./backend/dist/index.js"

ensure your package.json file has got an engines object; (recommended for deployment)
e.g engines: {
                "node": "18.1.0",
                "yarn": "1.22.18"
             }

e) save the file by saying; 
ctrl + x then shift + y then enter

f) install your project dependencies; yarn install

g) copy your environment variables; create the environment variable file as you have it locally 
e.g: cd backend/src/config && sudo nano .env

h) copy and paste the contents of the local env-file into the newly server .env file you can call the env file whatever 

name you perceive; but as programmed locally. Just ensure the extension is appended. Repeat step e.

i) spin the server: yarn start

j) rename the server: pm2 restart 0 --name plutonium_server

k) you can now run pm2 logs or pm2 list for monitoring

l) subsequently, all you need do next time is: pm2 start plutonium_server, pm2 stop plutonium_server etc

m) replicate this procedure; to deploy other instances.
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

Top comments (0)