Skip to content

Instantly share code, notes, and snippets.

@Eucrow
Last active June 25, 2022 08:45
Show Gist options
  • Save Eucrow/b94e18f94d3c83a733debefc307a24fb to your computer and use it in GitHub Desktop.
Save Eucrow/b94e18f94d3c83a733debefc307a24fb to your computer and use it in GitHub Desktop.
Deploy node app in ubuntu 16.04 server with MongoDB and PM2

Deploy node app in ubuntu 16.04 server

NODE

Install node

Follow instructions of node webpage: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

Recomended install build-essential

sudo apt-get install -y build-essential

Utils:

node --version

MongoDB

Follow instructions https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu/?_ga=1.261646340.820421326.1484596210.

Import the public key used by the package management system:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

Create the /etc/apt/sources.list.d/mongodb-org-3.4.list:

This file add the mongo repository.

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

Reload local package database

sudo apt-get update

Install

sudo apt-get install -y mongodb-org

Utils

sudo service mongod start

Create database with user for the app

mongo
use appdatabase
db.createUser({
  user: "appuser",
  pwd: "passworduser",
  roels: ["readWrite"]
  })

Improve security

Modify /etc/mongod.conf, adding in security section:

security:
  authorization: "enabled"

Configure to run mongodb in the server start

Create mongodb.service
sudo nano /etc/systemd/system/mongodb.service

Add to mongodb.service file:

[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target

[Service]
User=username
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

Run mongodb service

sudo systemctl start mongodb

Enable service to the server start

sudo systemctl enable mongodb

Utils

sudo systemctl status mongodb

Install the node app

Create user for the appname and lock account

sudo adduser appname
sudo passwd -l appname

Install the app

Follow its instructions to install it in the appname user

PM2

Install PM2 (process manager for node)

Install as root.

sudo npm install pm2 -g 

Start app with pm2

cd /route/
pm2 start app.js --name "AppName"

Save process list

pm2 save

Restart PM2 in the boot/reboot of the system

To restart PM2 in the boot/reboot of the server obtain the script required:

pm2 startup

And execute it as root.

Utils

pm2 unstartup appname
pm2 list









Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment