如何使用Fastify指定端口启动服务?NestJS集成场景下端口未监听问题排查
Let’s walk through the most common fixes for this issue, since your logs show the app starts successfully but the port isn’t appearing in netstat.
1. Check if the port is listening on IPv6
On many modern systems, 0.0.0.0 (IPv4) can be mapped to :: (IPv6). Run a broader check to see if port 3000 is in use anywhere:
- Windows:
netstat -ano | findstr ":3000" - Linux/macOS:
ss -tulpn | grep :3000
If you see a line with [::]:3000, that means Fastify is listening on IPv6, which should still accept connections from IPv4 clients (most systems enable IPv4-mapped IPv6 by default).
2. Use the options object for app.listen() instead of positional arguments
Sometimes positional parameters can lead to unexpected behavior with Fastify. Try passing an options object explicitly to avoid ambiguity:
import { NestFactory } from "@nestjs/core"; import { NestFastifyApplication, FastifyAdapter } from "@nestjs/platform-fastify"; import { AppModule } from "./app.module"; async function bootstrap() { const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter() ); // Use options object for clear, explicit binding await app.listen({ port: 3000, host: '0.0.0.0', }); console.log(`Server confirmed listening at http://0.0.0.0:3000`); // Add this to verify the bound address } bootstrap();
This ensures Fastify explicitly binds to 0.0.0.0 instead of falling back to default settings.
3. Verify Fastify and NestJS version compatibility
Mismatched versions between @nestjs/platform-fastify and fastify can cause subtle binding issues. Check your package.json to align versions:
- For NestJS v10+, you need Fastify v4.x
- For NestJS v9, Fastify v3.x is required
Run npm list fastify to see the installed version, and adjust if needed (e.g., npm install fastify@4.x for NestJS v10).
4. Test with a minimal NestJS + Fastify setup
If the above steps don’t resolve the issue, create a fresh project to isolate whether the problem is in your app’s code or environment:
nest new fastify-test --platform fastify cd fastify-test npm run start:dev
Check if this minimal app listens on 0.0.0.0:3000 using netstat. If it does, the problem is likely in your original app’s modules (e.g., a provider hanging during initialization, or middleware blocking the listen call).
5. Enable Fastify logging for deeper debugging
Add detailed logging to the FastifyAdapter to see exactly how the server initializes:
const adapter = new FastifyAdapter({ logger: { level: 'info', }, });
This will log the exact address and port Fastify attempts to bind to, helping you spot any configuration discrepancies.
内容的提问来源于stack exchange,提问作者Danstadje

