user3788756
user3788756

Reputation: 71

How do I access my node.js server via public IP address?

I want to get a response from a remote node.js server by typing my public IP address into my browser. When I type my public IP into my browser on my personal computer, I get "Unable to Connect". My node.js server isn't connected to the World =(

var http = require('http');//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response
  res.end(); //end the response
}).listen(3000, function(){
 console.log("server start at port 3000");
});

I've tried:

I have zero idea what I'm doing wrong and would be so grateful for your help.

Upvotes: 1

Views: 2608

Answers (2)

Ygautomo
Ygautomo

Reputation: 874

I think you are not open port 3000 on server's firewall, and no need to redirecting the traffic.

You have to ensure that the designated port (3000) is open to reach.

  1. Ensure the server is reachable ping IP_ADDRESS
  2. Check open port with iptables -L INPUT -v or ufw status verbose to see if that port 3000is open
  3. Update rules to open the port iptables -I INPUT -p tcp -m tcp --dport 3000 -j ACCEPT or ufw allow 3000
  4. Check again that the rules implemented iptables -L INPUT --line-numbers or ufw status verbose
  5. If still not reachable set host to 0.0.0.0 so it could reach from any ip
  6. Then try from your browser to reach the server IP_ADDRESS:PORT

Upvotes: 0

user3788756
user3788756

Reputation: 71

I eventually found the answer, thanks to Saddy's suggestion that the problem might be port forwarding.

1. I decided to use ports 3080 and 3443 for my node server.
2. I SSHed into my CentOs instance.
3. I disabled the default firewall, firewalld.
4. I set up port forwarding using iptables with the following commands:

firewalld stop

firewalld disable

iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT

iptables -I INPUT 1 -p tcp --dport 25 -j ACCEPT

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3080

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 3443

iptables-save > /etc/sysconfig/iptables

After this, I was able to access my node server via a browser.

Upvotes: 1

Related Questions