Deploy your first Node js and MongoDB app on google cloud

Rohit Singh
3 min readOct 30, 2020

Hello everyone,

Today, I am going to tell you how I deployed my first Nodejs and MongoDB app on node js on google cloud. Hope it will be helpful.

Let's start!

Guessing that you have built the app on local and everything works fine. In my case, my app flow diagram was somewhat like this:

So, in front of me, my first task was to host my node js server. And for that, I needed to first host the MongoDB database.

Step 1: Host MongoDB on google cloud from its marketplace section. Here I used MongoDB by bitnami. This creates a VM and costs around $7.5/month.

Step 2: You can open ssh and change password using:

Step 3: Import collection to MongoDB VM on the virtual machine using:

Step 4: Note for the host, port, username, password of your MongoDB VM. It will be needed for Nodejs server app. I recommend configuring your Nodejs app with cloud MongoDB instance and testing it on local.

Now, it is the time to host your Nodejs server.

Step5: Create a VM instance in the compute engine section.

Step 6: Open the ssh for the VM and install Nginx. Nginx is an open source software for web serving, reverse proxying, caching, load balancing, media streaming, and more. It started out as a web server designed for maximum performance and stability.

Step 7: Push your Nodejs code to GitHub and clone it to your VM.

Step 8: Install Nodejs, npm, and run command npm install inside the app folder to install all the dependency associated with the project.

Step 9: Run the app. Make sure to run the app on port 8080.

Now, you can test your Nodejs app server on the terminal using the command: curl http://<IP of your VM>:port/{route}

Step 10: Now make changes to default file in /etc/nginx/sites-available/ folder. Replace the file with the following code:

server{
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;

index index.html index.htm index.nginx-debian.html;
server_name _;

location / {

proxy_pass
http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection ‘upgrade’;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;

}
}

Step 11: Check for default nginx configuration and restart it using commands respectively:

sudo nginx -t

sudo systemctl restart nginx

Now, you can use your server from anywhere in the world. Congrats!

But there is one thing more. We want that our server should run it we even close the terminal and logout. For this, we can use pm2 or Process Manager 2. PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without the downtime and to facilitate common system admin tasks.

Final Step: Just run a few commands in your VM ssh.

npm install pm2

pm2 start ./bin/www

pm2 status

We are all set. Congrats!

--

--