使用PM2托管FreeFeed Node.js服务失败:进程启动但无端口监听
Hey there! Let's break down why your FreeFeed server works perfectly with yarn start but fails to listen on port 3000 when using PM2. Here are the most likely culprits and their fixes:
1. Missing Environment Variables
When you run yarn start, it's executing a script defined in your package.json that probably loads critical environment variables (like from a .env file) before launching the server. PM2 launching index.js directly skips this step, so your server might not have the configs needed to bind to port 3000 or connect to dependencies like databases.
Fixes:
- Check your
package.jsonstart script: Open/srv/myapp/package.jsonand look at thescripts.startentry. If it includes logic to load env files (e.g.,"start": "dotenv node index.js"), PM2 needs to replicate this. - Load env file with PM2: Run PM2 with the
--env-fileflag to pull in your environment variables:pm2 start index.js --env-file /srv/myapp/.env - Use a PM2 ecosystem config: Create an
ecosystem.config.jsin/srv/myappto formalize your setup:
Then start the server with:module.exports = { apps: [{ name: 'freefeed-server', script: './index.js', cwd: '/srv/myapp', env: { NODE_ENV: 'development', PORT: 3000, // Add other required env vars here (DB connections, etc.) } }] };pm2 start ecosystem.config.js
2. Incorrect Working Directory
PM2 might be running the process from a directory other than /srv/myapp, which means your server can't find config files, static assets, or even installed dependencies. Even if PM2 marks the process as "online", it might fail silently during initialization.
Fix:
- Specify the working directory when starting PM2:
Or add thepm2 start index.js --cwd /srv/myappcwdfield to your PM2 ecosystem config (as shown above).
3. Check PM2 Logs for Hidden Errors
Just because PM2 shows the process as "online" doesn't mean the server started successfully. There could be silent errors (like missing modules, database connection failures, or invalid configs) that prevent it from binding to the port.
Fix:
- View the PM2 logs for your app to uncover issues:
Look for error messages that explain why the server isn't listening on port 3000.pm2 logs index # Or use the process ID: pm2 logs 0
4. Verify Port Configuration
Double-check that your FreeFeed server is actually set to listen on port 3000. Many apps use environment variables to define the port, so if that variable is missing (as in issue #1), it might default to a different port or not listen at all.
Fix:
- Check your server's code or config files to confirm the port setting. If it uses
process.env.PORT, ensure this variable is properly set in your PM2 setup.
内容的提问来源于stack exchange,提问作者narad

