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}/`);
});
最佳答案
不要尝试监听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}`);
});