Running Node server on VM - LupodeLupis/BrightIdeas GitHub Wiki
This step is only needed on a new VM without Node.js.
Configure VM
-
SSH to your VM
-
Go into the student directory
cd /home/student
- Get VM ip address
ip addr
Output: 1.lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet xx.xx.xx.xx/x scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2.ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff inet xx.xx.xx.xx/20 brd xx.xx.xx.xx scope global dynamic ens160 valid_lft 2930sec preferred_lft 2930sec inet6 xxxx::xxx:xxxx:xxxx:xxx/xx scope link valid_lft forever preferred_lft forever
-
Copy the IP address in bold from above.
-
Create a server file
sudo nano server.js
- Copy and paste the code below. Replace the 'ip_address' with your VM IP address from step 4. Then ctrl-x to save and exit.
const http = require('http');
const hostname = ' ip_address’;
const port = 10034;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.send('Node JS - Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Installing Node.js
- Install curl in case it is not installed on your VM
sudo apt install curl
- Get the latest stable version of nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
- Install Nodejs on the VM. Press 'y' when prompted.
sudo apt install nodejs
- Use the commands below to view the version number installed.
node -v
npm -v
- Start the Nodejs service
sudo node server.js
Updating node.js for Angular CLI
- Clear NPM cache
sudo npm cache clean -f
- Install nodejs globally
sudo npm install -g n
- Install latest version
sudo n stable
Running Node Server Continuously
- Install forever
sudo npm install -g forever
- Run node processes continuously
forever start server.js
- Check forever to ensure server.js is running
forever list