Deploying Node.js Apps for Production on Alibaba Cloud

Introduction

Prerequisites

Step 1 — Installing All Server Dependencies

Installing Git

sudo apt-get install git

Installing Node.js

curl -sL https://deb.nodesource.com/setup_8.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt-get install -y nodejs

Installing Nginx

sudo apt-get install nginx

Installing PM2 Process Manager

npm i -g pm2

Step 2 — Getting the Application Code

Cloning the Application Code

cd /home
git clone https://github.com/bahdcasts/node-js-blog.git

Installing Project Dependencies

cd /home/node-js-blog
npm install

Setting up Environment Variables

cd /home/node-js-blog
nano .env
PORT=3000
DB_URI=
CLOUDINARY_API_KEY=xxxx
CLOUDINARY_API_SECRET=xxxx
CLOUDINARY_NAME=xxx
EXPRESS_SESSION_KEY=d29z4944SxETKPNWqKAkCNUjrZ4A

Step 3 — Connecting to the MongoDB Instance

Whitelisting Our Server IP on ApsaraDB for MongoDB

Setting up DB_URI Connection String

Setting the DB_URI Environment Variable

PORT=3000
DB_URI="mongodb://root:passWORD1234@dds-gs50fb23291731d41.mongodb.singapore.rds.aliyuncs.com:3717,dds-gs50fb23291731d42.mongodb.singapore.rds.aliyuncs.com:3717/admin?replicaSet=mgset-300215248"
CLOUDINARY_API_KEY=132255634713478
CLOUDINARY_API_SECRET=aeBNzdZFcju9ZEAiL7KsEMbBlFI
CLOUDINARY_NAME=bahdcoder
EXPRESS_SESSION_KEY=d29z4944SxETKPNWqKAkCNUjrZ4P

Step 4 — Setting up the Nginx Configuration

# Empty the current configuration file
echo > /etc/nginx/sites-available/default
# Open the file using nano
nano /etc/nginx/sites-available/default
server {
listen 80;
server_name 47.88.230.255; location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}
sudo systemctl restart nginx

Step 5 — Starting the Application

cd /home/node-js-blogpm2 start index.js --name "blog"

Tracking Application Logs

pm2 logs blog

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store