Phillip YS
Phillip YS

Reputation: 904

Can't connect to Node server on Amazon EC2

Here's the app.js, the code is too long so that's why I'm showing this code only, there's no problem in other code I assume this is a network problem.

app.js

app.listen(8080, 'localhost', function () {
    console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});

I don't get any response when i run lsof -i :8080. but I do get response when I run curl localhost:8080 on the server.

and I don't think there's any problem with security group. I allowed any ip to access to the instance as you can see below.

enter image description here

and here's actually how it looks like when I test public ip and localhost

ubuntu@:ip~/$ curl -v 18.217.107.76:8080
* Rebuilt URL to: 18.217.107.76:8080/
*   Trying 18.217.107.76...
* connect to 18.217.107.76 port 8080 failed: Connection refused
* Failed to connect to 18.217.107.76 port 8080: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 18.217.107.76 port 8080: Connection refused
ubuntu@ip:~/$ curl -v localhost:8080
I get response here!

Upvotes: 0

Views: 4344

Answers (2)

Ankit Tiwari
Ankit Tiwari

Reputation: 1239

This is what worked for me!!

In your security group you have added the rule HTTP which listens by default on port 80.

So basically if you have configured your node server to run on a port other than port number 80 (I was doing this mistake) and try to access the public DNS(EC2 public DNS can be found in instance description) on browser, connection refused error might come so what you can do is change the PORT value in the config to 80.

Your config.env will look like this

PORT=80

And in your server.js you can write

const PORT = process.env.PORT;
try {
    app.listen(PORT, () => { console.log(`server running at port ${PORT}`) })
} catch (error) {
    console.log(error)
}

Upvotes: 1

Phillip YS
Phillip YS

Reputation: 904

I changed the code from

app.listen(8080, 'localhost', function () {
    console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});

to

app.listen(8080, function () {
        console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
    });

now it's working

Upvotes: 7

Related Questions