Setting up a nodejs app on gcloud compute engine

1. In the Compute Engine dashboard in gcloud console, click create new instance.
2. On new instance creation page, for name, it can be any name you desire. For region, you can choose the region that is closer to your app user, but it doesn’t matter much since this is just for testing. For machine configuration, select micro since it is just for testing.
3. For os version under the boot disk, select Ubuntu 18.04 LTS or any other os that you are most familiar with.
4. Under firewall, only check the Allow HTTP traffic. Check Allow HTTPS traffic only if you have ssl certificate for your app server.
5. Click Create.
6. Click SSH next to the instance after it is created, it will bring up a new shell window connecting to the instance.
7. Run this to update the package manager.

sudo apt-get update

8. Download node version manager

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

9. Activate node version manager, nvm

. ~/.nvm/nvm.sh

10. Install latest node version

nvm install node

11. Check node is installed and running correctly

node -e "console.log('Running Node.js ' + process.version)"

12. Create a dir myapp and cd into it

mkdir myapp
cd myapp

13. Let’s create a simple node server, create a file called hello.js and put the following in it. Open vim vim hello.js, Press I for insert, and Ctrl-v to paste the following code, then Press ESC, then type :x, and then press enter to save.

// Load the http module to create an http server.
var http = require('http');
 
// Configure the HTTP server to print Hello World! to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World!\n");
});
 
// Listen on port 8080
server.listen(8080);
 
console.log('Server available at http://localhost:8080/');

14. Install pm2 for running your node server

npm install -g pm2

15. Start server with pm2

pm2 start index.js --watch

16. Redirect port 80 to 8080, so your node server can be reached from the browser.

sudo iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT
sudo iptables -t nat -A OUTPUT -o lo -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Enable https with nginx

Search within Codexpedia

Custom Search

Search the entire web

Custom Search