Search code examples
amazon-ec2aws-security-group

Cannot hit simple node web server hosted on EC2 instance


Not able to hit my simple node web server hosted on an ubuntu EC2 in AWS. But I can't see I've missed anything! I've provided screen shots below within AWS - What am I missing? Please help!. Many thanks,

Node code

const http = require('http');

const hostname = '127.0.0.1';
const port = 8080;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Command prompt

$ node index.js 

Command prompt response

Server running at http://127.0.0.1:8080/

EC2 instance

ec2 settings

Security settings

security settings

Elastic IP settings

enter image description here

Browser

http://"Public DNS (IPv4) value":8080/ 

Update

enter image description here


Solution

  • When you select the type, select "Custom TCP Rule":

    Port Rules

    and enter 8080 in the port range field.

    EDIT

    However, that only gets you part of the way. If you notice, your server is listening on the IP address 127.0.0.1. That means that it's not listen to the outside world, only localhost. To access it outside of the server machine you'll need to change your code to:

    const http = require('http');
    
    const hostname = '0.0.0.0';
    const port = 8080;
    
    const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello World\n');
    });
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    

    The change is that you're now listening on "all interfaces" as compared to just localhost.