You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何强制Node.js(PM2托管)监听IPv4以适配防火墙限制?

Fixing Express App to Listen Only on IPv4

Hey there, let's get your Express app working with your host's new firewall rules right away! The issue here is that by default, Node.js (and Express) will listen on both IPv4 and IPv6 interfaces when you only specify a port. Since your host blocked IPv6 HTTP connections, we need to force the app to bind exclusively to IPv4.

Here's how to modify your code:

You were on the right track with using http.createServer(app).listen(), but you can actually simplify this directly with Express's app.listen() method—it supports passing an IP address as the second parameter. Plus, don't forget to update your Socket.IO server too, since it might also be listening on IPv6 by default.

Modify your mongoose success callback like this:

mongoose.connect(MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
  .then(result => {
    // Force Express to listen on IPv4 only
    app.listen(APP_PORT, '0.0.0.0', () => {
      console.log(`Express app listening on IPv4: http://0.0.0.0:${APP_PORT}`);
    });

    // Also update Socket.IO server to use IPv4
    socketServer.listen(SOCKET_PORT, '0.0.0.0', function () {
      console.log('Socket server listening to: %j', socketServer.address());
    });
  })
  .catch(err => {
    console.error('Connection error:', err);
  });

Key Notes:

  • Using '0.0.0.0' tells Node.js to bind to all available IPv4 network interfaces (this is the standard way to make your app accessible externally on IPv4). If you need to bind to a specific IPv4 address (like your server's public or private IPv4), you can replace '0.0.0.0' with that exact address instead.
  • After making this change, check your server logs: the Socket.IO address should show address: '0.0.0.0' instead of '::' (which is the IPv6 wildcard address). This confirms it's only listening on IPv4.
  • The http.createServer(app).listen(APP_PORT, APP_IP) approach you mentioned also works perfectly—Express's app.listen() is just a wrapper around that under the hood, so either method will achieve the same result.

Once you deploy this change, your app should comply with the host's firewall rules and start accepting IPv4-only HTTP connections again!

内容的提问来源于stack exchange,提问作者Arash Rabiee

火山引擎 最新活动