Can't connect to Node web-server hosted on Ama

2019-05-30 03:05发布

问题:

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.

  1. What is wrong with my server code?

  2. 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.

回答1:

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:

  1. Open the port (in your case 1223) in the security groups of your instance.
  2. 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.



回答2:

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.