Running Next.js in the Background


There are several ways to run your Next.js application in the background. Below are two common methods.

1. Using nohup Command

The nohup command allows the process to continue even after the terminal is closed. It can be used as follows:

nohup yarn start &

This command starts the Next.js server in the background and continues to run even if the terminal is closed. Logs are written to a file named nohup.out by default.

2. Using pm2

pm2 is a tool to daemonize and manage Node.js applications. It enables features like crash recovery, log management, and reloads without downtime.

To install pm2, you can do as follows:

sudo npm install pm2 -g

To run a Next.js application using pm2, you can do as follows:

pm2 start yarn --interpreter bash --name my-app -- start

Here, my-app represents the name of the application, and start is the script name to run.

To manage your application with pm2, you can use the following commands:

  • pm2 stop my-app : To stop the application
  • pm2 restart my-app : To restart the application
  • pm2 delete my-app : To delete the application
  • pm2 list : To list all managed applications

While both of these methods run the application in the background, for long-running production environments, it is recommended to use a process manager like pm2. This allows for convenient features such as automatic recovery from crashes and log management.