In my last post, I got my Node app running on EC2 with npm start. It worked until I closed the terminal. Then it was gone.
This post fixes that with PM2. It takes about 5 commands.
Why the app stops
When you run npm start over SSH, the app is a child of your shell. Close the SSH window and the shell exits, so the app exits with it. Ctrl+C does the same thing on purpose.
A server needs the app to run with nobody logged in. That's what a process manager is for.
1. Install PM2
npm i -g pm2 If you get permission denied, your global npm folder belongs to root. Run it with sudo:
sudo npm i -g pm2 2. Start the app with PM2
From inside the project folder:
pm2 start index.js --name node-api PM2 prints a table with an ID (0) and the name you gave it. The app is now running in the background. You can close your SSH session, and it keeps running.
3. Check the logs
You no longer see the app's output in your terminal. To read it:
pm2 logs node-api You can also use the ID: pm2 logs 0. Press Ctrl+C to stop watching the logs. That doesn't stop the app.
4. See what's running
pm2 list This shows every app PM2 manages, its status, CPU, memory, and restart count. A rising restart count means your app is crashing.
5. Start it again after a reboot
PM2 keeps the app alive while the server is up. If the EC2 instance reboots, PM2 itself needs to start again. Two commands handle that:
pm2 startup This prints one sudo env PATH=... command. Copy it and run it. It registers PM2 as a system service.
Then save the current list of apps:
pm2 save Now, after a reboot, PM2 starts and brings node-api back on its own. Test it with sudo reboot, SSH back in after a minute, and run pm2 list.
Next
The app runs on port 4000. Next, I put Nginx in front of it so people can reach it on port 80.
Video
Here's the 4-minute walkthrough:
Previous step, run the app with npm start: https://dev.to/jahidhiron/run-a-nodejs-app-on-aws-ec2-and-why-it-stops-when-you-close-ssh-3bb5
Full course playlist: https://www.youtube.com/playlist?list=PLfeDvEEUyoEJZGnw11rKIET5lJDs6JmhD
