Lucas Tesseron
Lucas Tesseron

Reputation: 444

Is Angular 19.0 incompatible with pm2?

I can't get pm2 to work with a fresh Angular 19.0 build.

Here's what I’ve tried:

The node server is not listening on any port. The process appears online in pm2, but it doesn't log anything.

When I launch the server directly using node dist/server/server.mjs, the server starts up and runs as expected. If I downgrade to angular 18.2, the server runs as usual with pm2.

Environment:

I have no clue what's happening since the logs are empty. How can I debug this?

Upvotes: 2

Views: 328

Answers (2)

Visually1
Visually1

Reputation: 31

I found a solution to this problem. It seems Angular 19's server.mjs module structure requires explicit handling for PM2 environments.

The issue occurs because the server only starts when it's the main module, but PM2 changes this behavior. Here's how to fix it:

  1. Modify your server.mjs:
export function startServer() {
  const port = process.env['PORT'] || 4000;
  app.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

const metaUrl = import.meta.url;
const isMain = isMainModule(metaUrl);
const isPM2 = process.env.PM2 === 'true';

if (isMain || isPM2) {
  startServer();
}
  1. Create/update your PM2 ecosystem file:
module.exports = {
  apps: [{
    name: "angular-app",
    script: "dist/server/server.mjs",
    env: {
      PM2: "true"
    }
  }]
}
  1. Start with: pm2 start ecosystem.config.js

This works because it explicitly checks for both the main module condition and a PM2 environment flag. The server will now start correctly under PM2.

Hope this helps someone else running into the same issue with Angular 19!

Upvotes: 3

Lucas Tesseron
Lucas Tesseron

Reputation: 444

I'll answer my own question as I figured it out. In the default generated server.ts file when creating a new app, the following lines appear at the end of the file:

/**
 * Start the server if this module is the main entry point.
 * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
 */
if (isMainModule(import.meta.url)) {
  const port = process.env['PORT'] || 4000;
  app.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

The isMainModule function comes from the @angular/ssr package and "Determines whether the provided URL represents the main entry point module." However, PM2 uses a container around the Node process to manage it (see pm2/lib/ProcessContainerFork.js). As a result, the function failed to determine that it's the main module who call it, the condition is never met, and the process stops there.

Upvotes: 2

Related Questions