node.js install on Amazon EC2 - node.js

So I'm installing node.js on amazon ec2 with ubuntu 8.04, and and have run node sayhello.js which is this code:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
setTimeout(function () {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<br/><strong> Hello World!</strong>');
res.end();
sys.puts(sys.inspect(req, false));
}, 2000);
}).listen(8000);
sys.puts('Server running at http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/');
I see
Server running at
http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/
being displayed in the console correctly.
The tutorial says: go to :8000 in the browser and you should see Hello World!
I go to http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/ (not the real address) but it doesn't load (just connecting...). The example uses localhost, is doing the public domain incorrect or some such?
Thanks.

You need to open up port 8000 in your security group.
If you've got the EC2 command line tools installed, try running:
$ ec2-authorize default -p 8000
This assumes that you're using the default security group. If not, change default to the name of your security group.
If you're just using the web interface follow these steps:
Login to the AWS console
Select Amazon EC2 in the top bar
Click on Security Groups in the menu on the left
Click on the security group that you assigned to your EC2 instance (probably just default)
In the bottom window pane, click on the Inbound tab
Set Port range: to 8000 and leave the other two inputs as they are
Click Add Rule

Within the security group associated with the EC2 instance, make sure you have port 8000 open to your IP or to the public.

Check the following:
That you are allowing access from all ips to port 8000 in the security group
That you have modified the CORRECT security group (e.g., quicklaunch-1) and not, say, quicklaunch-2. I've edited the wrong one more times than I care to admit.
That you have opened port 8000 on the Linux firewall
That your server is actually running (you should see "Listening on port 8000" in the command line).
Here is a tutorial on how to set up a Node.js web server on Amazon EC2: http://www.lauradhamilton.com/how-to-set-up-a-nodejs-web-server-on-amazon-ec2
It's a bit more complicated than what you're doing (because it uses ip forwarding from 80 to 8080) but the part about opening the Linux firewall is the same.

Related

dns server configuration for node.js

I have developed server application in node.js. Right now I access the application using 128.1.1.5:3000. But i want to use a domain name like abc.net to access the application. How can I do this. Please suggest.
To configure DNS on your local app,you need to do following configuration.
Make an entry of this DNS example abc.net as a host instead of local host while setting up your node server where you are mentioning the localhost host and port detail eg. in app.js file.
Example
const http = require('http');
const hostname = 'abc.net';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Now open command prompt and type
ipconfig -all
It will list all your IPs. Select the ip of your machine which is preferred one.mostly you can locate this ip by finding the ip which is followed by (preferred) keyword in command prompt.
Now copy this IP address and make an entry of this in system host file.Make sure you have an admin rights to make changes in this file.
Path of host file in Windows
C:\Windows\System32\drivers\etc\hosts
Edit this file and scroll to the end and press Enter to copy the ip address corresponding to the DNS which you have configured in node js application as shown below in new line.
IPaddress(fetched in step 3)
abc.net
i.e ipaddress then give space then dns name
Save the file.
Start your node application.
Now try hitting your api from the url abc.net:port/api
You will need a domain that you can edit the DNS settings on and add an A record that is configured to your server's external IP address
then you can access your domain with the port attached
example: mydomain.com:5000
you should refer to your domain record provider's documentation on how to do this.
Beyond that, you may encounter firewall settings, port settings, and possible HTTPS certificates issues but these are separate topics each.

Google App Engine 502 (Bad Gateway) with NodeJS

I have a full web application using NodeJS, MongoDB (Mongoose as the driver) and ExpressJS.
The project works perfectly on my local machine. Today I decided to move everything to production. I'm using Google App Engine to host my application, and Compose (formally MongoHQ) to host my database.
App Engine servers my application perfectly, although my API does not seem to work. My API is served from example.com/api, and each request (GET, POST, DELETE and PUT) all returns a 502 (Bad Gateway) error.
I tried running my application on my local machine while connected to my remote MongoDB database and that worked perfectly fine. So it must be a problem with App Engine or NodeJS, not with MongoDB.
I have tried checking all error logs within Google Cloud, although there are no errors.
Why is App Engine/NodeJS serving my application's static content perfectly fine, although not allowing any requests to my API?
just make sure that your server listens on 8080 port
https://cloud.google.com/appengine/docs/flexible/custom-runtimes/build#listen_to_port_8080
502 Bad Gateway is usually an error on the Nginx side. Unfortunately those logs are not surfaced to Cloud Logging, yet.
A lot of times the problem is that your HTTP packets are too big for the buffers or something similar. The way you can see the nginx log is something like this:
Use just 1 VM. This isn't strictly necessary, but a lot of times it makes it easier to debug your application if you know that your requests on the one machine. You can accomplish this by adding this to your app.yaml:
manual_scaling:
instances: 1
then re-deploy
Switch the VM from "Google owned" to self-managed. This can be done in the Cloud Console. Go to Compute Engine, instances, click on the instance name that matches the App Engine version, and you should see an option to switch it to self-managed.
gcloud compute ssh <instance name> to SSH to the machine
docker ps to see your running containers. Look for the container named nginx and grab its id.
Once you have a container ID, you should be able to docker exec -it <container id> -- cat /var/log/nginx/error.log. You might want to ls that whole log directory.
You will likely see an error there which will be a bigger hint as to what's going wrong.
I know this is way more complicated than it should be :-\ If you have any problems with the steps above, leave a comment. If you do find an error and you're not sure what to do with it, also leave a comment.
I had the same problem, I was getting "nginx 502 bad gateway" error on GAE standard environment. There are many reasons for this but I finally got it working. Try these:
1) Run the app on the correct port. Google will set the PORT environment variable. I was running on port 8080, in the stackdriver logs I was getting this warning:
App is listening on port 8080. We recommend your app listen on the
port defined by the PORT environment variable to take advantage of an
NGINX layer on port 8080.
The code below gets the port from environment, if PORT is set otherwise defaults to 8080:
const PORT = process.env.PORT || 8080;
2) Go to google cloud console -> logging -> logs viewer. Select Google App Engine and then your service from the down and check you logs. Are you getting the requests at all or does it look like the requests do not react to your server. In my case, I was not getting them even after I fixed the port:
2020-03-02 21:50:07 backend[20200302t232314] Server listening on port
8081! 2020-03-02 21:50:08 backend[20200302t232314] "GET /create-user
HTTP/1.1" 502
Fix any error if it looks like your application is failing to start, throwing exceptions etc..
3) Don't pass an IP when you are running your server. It seems Google runs the app at a pre-defined IP address and do not want you to modify it:
server.listen(PORT);
4) Don't try to run on https! Google is running an nginx server in front of your app and it is handling the SSL and redirects to your app over http. You can use the environment variable NODE_ENV(it is set to "production" in GAE environment) to run on http on production and https elsewhere, like this:
let https = require('https');
let http = require('http');
if (process.env.NODE_ENV == "production") {
http.createServer(app).listen(PORT, function () {
console.log(`Server listening on port ${PORT}!`)
});
} else {
https.createServer({
key: fs.readFileSync('host.key'),
cert: fs.readFileSync('host.cert')
}, app).listen(PORT, function () {
console.log(`Server listening on port ${PORT}!`)
});
}
5) I didn't need to set any handlers in my yaml file, it might be causing errors for you if you have incorrect configuration. My yaml file is pretty straightforward:
runtime: nodejs12
env: standard
instance_class: F1

Can't connect to Node web-server hosted on Amazon EC2

I'm running a node app on an Amazon EC2. The app includes a simple web server intended to serve the index page, but it doesn't work.
Here's the server code:
var http = require('http'),
fs = require('fs'),
io = require('socket.io'),
index;
fs.readFile('client.html', function(err, data){
if (err){
throw err;
}
index = data;
});
var server = http.createServer(function(request, response){
response.writeHeader(200,{"Content-Type": "text/html"});
response.write(index);
response.end();
}).listen(1223);
The EC2 is assigned the public IP address 54.187.31.42. I run the app, open my browser, connect to 54.187.31.42:1223 expecting to be served a web page and get nothing.
What is wrong with my server code?
I used the snippet found in this answer to check the IP of the EC2 running the app, and oddly get 172.31.3.67 - why is the returned address different from the one assigned to the machine by Amazon?
Consequently, trying to connect to 172.31.3.67:1223 also fails.
Straight from the Amazon dev controls, if that helps confirm it isn't an issue of the server IP being wrong or something.
The code looks fine, try connecting with the public IP/public DNS that you see in the AWS console.
Try the following and your application would work:
Open the port (in your case 1223) in the security groups of your instance.
stop the firewall on your machine (i.e. iptables) and now access your server using public ip or public DNS.
If you can now acceess your machine that means something in the iptables is filtering your traffic. You can modify the iptables rules accordingly.
In security group, add a rule with the type "Custom TCP Rule" on the used port (e.g. port: 3000 or 1223 for this case). It works for me.

Node.js: Cannot access server from different device on the same network

NOTE: There are some others who have had similar problems, but those were solved by fixing small tidbits in the code involving how the server was listening (in examples that I've seen they put '127.0.0.1' as an argument in http.createServer(...).listen(). However, I do not have the same issue.
When I try to connect to my node.js server from a different machine on the same LAN network, Chrome says that it cannot connect.
This is testtesttest.js
var http = require('http');
http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type': 'text/plain'});
res.end('Working');
}).listen(3000);
When I try inputting 192.168.1.73:3000 (of course 192.168.1.73 is the ip of the machine that I'm running the server on) into the browser (Chrome, although I've tried other browsers as well and I have similar problems) of my other machine, it gives the error "Oops! Google Chrome could not connect to 192.168.1.73:3000". When I type the same address onto the local machine, it works fine.
I'm not exactly sure what to do. I honestly hope this is just a stupid mistake on my part (I'm sorry for possibly wasting your time) and not something that I have to go into my router for.
Thanks very much for any help.
Try changing this
.listen(3000);
to this
.listen(3000, "0.0.0.0");
Just putting this here in case it saves anyone else. I had this problem for two full days when trying to connect my phone to my local machine... and it was because the wifi on my phone was turned off.
I too had this problem.
I solved it by allowing "node.js" in the network group.
Solution : Allowing "node.js" through the private network windows firewall
a. Go to Control Panel
b. Go to Windows Firewall
c. Click on the Allow an app or feature through windows firewall in the left sidebar
d. Search for "Node.js : Server Side JavaScript" and make sure both public and private column box is marked tick for "NodeJS"
e. Click "OK" and you are done
Below is the step i followed which Worked
My server code
var http=require('http');
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/plain'});
response.end('Im Node.js.!\n');
console.log('Handled request');
}).listen(8080, "0.0.0.0");;
console.log('Server running a http://localhost:8080/');
Added inbound Rules.
Created a udp inbound rule(since i could'nt find any http protocol).
Once created go to properties for the created rule.
Choose Protocols and Properties tab.
Choose any in Port Type. Click apply and Ok. Now i tried from other
machine it worked!!!
I think you need to set Port Type to any to make it work.
Thanks
You have to open 3000 port so that it can be accessed from remote machines. You can do that in iptables file. Use below command to open file
vi /etc/sysconfig/iptables
now add below line before the reject lines in that file
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
Now restart iptables service using below command
service iptables restart
Now you restart your server and try again. It should work..
Chances are your firewall settings block incoming request on port 3000. You may want to add firewall inbound rule on this port to allow access to it.
For me, the culprit was a VirtualBox Host-only Network interface. The presence of this network interface was causing ipconfig on the server to report 192.168.56.1 instead of the router assigned address of 192.168.1.x. I was accessing the wrong IP all along.
To remove the VirtualBox Host-only Network interface:
Open VirtualBox
Go to File>Preference>Network>Host-only Networks
Remove the offending adapter(s)
My problem was that, I have used IP assigned to my ethernet adapter instead of wifi adapter...
And it now works when I connect from any device.
http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type': 'text/plain'});
res.end('Working');
}).listen(3000, "192.168.1.36");
I found my IPv4 address on network settings, then specify with listen fun. put also 3000 port. I can reach http://192.168.1.36:3000/ via my tablet which is connected same wifi.
You have to run that on the terminal:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Explanation here
Like what Umamaheswaran answered, a new inbound rule needs to be created. But instead of using the UDP protocol, I have to use TCP. My application runs on a Windows Server 2012. The Inbound Rules are set in Windows Firewall with Advanced Security, under Administrative Tools
I solved this using this algorithm. What it does is get all ip info from os.networkInterfaces, get all keys and loop trough it, filter by objects that contains family == "IPv4" and get it address value. After, it looks for '192.168.0.xxx' pattern and put it in possible_ip array. Any other ip will be pushed to other_ips array.
The export sentence is to turn it into a module js file.
import by import {get_ip} from ./your_path/name_of_your_file.js, or in common js const { get_ip } = require("./your_path/name_of_your_file.js");
Hop it helps
const os = require('os');
const _ = os.networkInterfaces();
// if common js use
// exports.get_ip = () => {
export const get_ip = () => {
let ips = [];
Object.keys(_).map(key => {
let ipv4_obj = _[key].filter(obj => obj.family === "IPv4")
let ipv4 = ipv4_obj[0].address
ips.push(ipv4)
})
let other_ips = []
let possible_ip = []
ips.map(ip => {
ip.includes("192.168.0.") ?
possible_ip.push(ip) :
other_ips.push(ip)
})
return { possible_ip, other_ips }
}

I can't access my node.js server on my AWS EC2 isntance from the outside

I'm trying to run a basic node.js server,
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('hello world!\n');
}).listen(3000, '0.0.0.0', function() {
console.log('Server running on port 3000');
});
However when I run it and go to http://x.x.x.x:3000/ the page doesn't load.
I tried the answer on this question but that didn't work either. And changing the host to 127.0.0.1 or the server ip or emitting it doesn't fix it either.
I've also followed this guide that says to proxy requests with haproxy. But that did not work either.
Is there something in the security tab I have to enable/disable?
Edit: The problem was I was using the wrong IP. The IP changes when the instance is restarted.
Create a rule to open port 3000 in the security group associated with your ec2 instance.
It can be done through the command line tools or through the web console, which is more straightforward. If you didn't specify a security group when creating the instance it will be the "default" security group.
A decent walkthrough for the console
Amazon documentation
Rightscale explanation of different firewall situations

Resources