Node js应用程序在本地工作正常。尝试在服务器上运行时显示错误。
ubuntu@ip-172-*-*-*:~/sample_nodejs$ node main.js
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRNOTAVAIL 52.*.*.*:1122
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1350:19)
at listenInCluster (net.js:1408:12)
at doListen (net.js:1517:7)
at _combinedTickCallback (internal/process/next_tick.js:141:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:695:11)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
这是我的端口运行状态。使用的命令 netstat -tulpn
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
PID/Program name
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN
-
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
-
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
-
tcp6 0 0 :::22 :::* LISTEN
-
tcp6 0 0 :::80 :::* LISTEN
-
udp 0 0 127.0.0.53:53 0.0.0.0:*
-
udp 0 0 172.*.*.*:68 0.0.0.0:* -
尝试更改iptables
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000
它仍然显示错误。这是服务器故障还是我需要服务器端的许可?
这是我使用公共IP地址尝试的示例代码:
var express = require('express');
var app = express();
const http = require('http');
const hostname = '52.*.*.*';
const port = 1122;
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}/`);
});
答案 0 :(得分:1)
不要尝试监听EC2实例上的外部IP地址-它不可用。相反,请在“ any”界面上收听(有时显示为0.0.0.0
)。根据文档,我可以找到server.listen来完成此操作,而无需指定主机参数:
如果省略
host
,则服务器将接受 unspecified IPv6 address(::
)在IPv6可用时,或者 否则unspecified IPv4 address(0.0.0.0
)。在大多数操作系统中,收听unspecified IPv6 address (
::
)可能导致net.Server
也收听unspecified IPv4 address(0.0.0.0
)。
您将监听的端口可以从外部访问,尽管您必须将其暴露给安全组。
编辑
您需要将代码更改为:
var express = require('express');
var app = express();
const http = require('http');
const port = 1122;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, () => {
console.log(`Server running at on port ${port}`);
});
答案 1 :(得分:1)
正如stundbar所说,在创建服务器时,您不必设置公共IP,而应设置0.0.0.0或localhost。 不要设置127.0.0.1,因为您将无法在服务器计算机之外访问它。