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

Node.js服务重启遇EADDRINUSE端口占用问题求助

Fixing EADDRINUSE on Nodemon Restart (Graceful Shutdown with SIGTERM)

Absolutely, using process.on('SIGTERM', ...) is the perfect solution here—this is exactly how you resolve the issue where your old server process lingers and holds onto port 4000 when nodemon tries to restart your app. Let me break down why this happens and how to implement the fix properly.

Why This Occurs

When nodemon detects a file change, it sends a SIGTERM signal to the running Node.js process to shut it down, then spins up a new instance. The problem with your current code is that your GraphQL Yoga server isn't listening for this signal, so it never properly closes the HTTP server and releases the port. The old process keeps running in the background, causing the "address already in use" error when the new process tries to bind to 4000.

Step-by-Step Fix

First, you need to capture the HTTP server instance returned by server.start()—GraphQL Yoga's start() method actually returns a standard Node.js http.Server object, which has a close() method to gracefully shut down the server. Then, you'll listen for the SIGTERM signal and trigger that shutdown.

Here's your updated server code:

const server = new GraphQLServer({ typeDefs, resolvers });

// Capture the HTTP server instance returned by server.start()
const httpServer = server.start({ port: 4000 }, () => {
  console.log('The server is up on port 4000!');
});

// Handle SIGTERM to gracefully shut down the server
process.on('SIGTERM', () => {
  console.log('🔌 Received shutdown signal (SIGTERM) — closing server');
  
  httpServer.close((err) => {
    if (err) {
      console.error('❌ Error shutting down server:', err);
      process.exit(1);
    }
    console.log('✅ Server closed successfully — port 4000 released');
    process.exit(0);
  });

  // Fallback: Force exit after 5 seconds if shutdown takes too long
  setTimeout(() => {
    console.error('⚠️ Server shutdown timed out — forcing exit');
    process.exit(1);
  }, 5000);
});

Additional Tips

  • Verify Nodemon Signal Behavior: Nodemon uses SIGTERM by default for restarts, but if you've modified your nodemon config, double-check that it's not using a different signal (like SIGKILL, which can't be caught).
  • Update Nodemon (Optional): Your current nodemon version (1.17.5) is quite outdated—updating to a newer version (e.g., npm install nodemon@latest --save-dev) can fix some edge cases around process management.
  • Check for Unrelated Process Leaks: If you still run into issues, use tools like lsof -i :4000 (macOS/Linux) or netstat -ano | findstr :4000 (Windows) to confirm if any unrelated processes are holding the port.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:21:07