You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS EC2中Fastify服务器无法访问但Node.js内置http服务器正常

问题排查与解决方案

核心原因

Fastify 默认只监听 localhost(127.0.0.1),这意味着只有EC2实例内部能访问,外部请求根本打不进来。而Node.js内置的http服务器默认监听所有网卡(0.0.0.0),所以外部能正常访问。

修复方法

修改Fastify的监听配置,指定host为0.0.0.0,让服务器监听所有可用的网络接口:

const fastify = require('fastify')({})

// 声明路由
fastify.get('/', async (request, reply) => {
  return { hello: true }
})

// 启动服务器
const start = async () => {
  try {
    const port = 3000
    // 添加 host: '0.0.0.0' 配置
    await fastify.listen({ port, host: '0.0.0.0' })
    console.log('🚀 Fastify Server Listening on Port ', port)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()

验证步骤

  1. 重启修改后的Fastify服务器
  2. 用EC2的公网IP或域名访问http://<EC2公网IP>:3000,应该能收到{ "hello": true }的响应
  3. 可以在EC2实例上执行netstat -tulpn | grep 3000,确认Fastify是否绑定到0.0.0.0:3000(而不是127.0.0.1:3000)

补充说明

  • 本地开发时用localhost足够,但部署到云服务器必须监听所有网卡才能接收外部请求
  • 如果要限制访问来源,别靠监听特定网卡,直接在Fastify路由或插件里加IP白名单更靠谱

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:37:04