Node.js ยท Chapter 42 of 43

Deploying a Node.js App

Deployment means making your app accessible on the internet, running on a server, cloud platform, or container. Common options include Render, Railway, Heroku, AWS, and Docker containers.

Preparing for deployment involves setting environment variables, configuring a start script, and often using a process manager for reliability.

Preparing your app

Make sure your `package.json` has a `start` script, remove hardcoded config in favor of environment variables, and specify a Node engine version.

Process managers

Tools like PM2 keep your app running, automatically restarting it on crashes and enabling clustering in production.

Example 1 (javascript)
// package.json
"scripts": { "start": "node server.js" },
"engines": { "node": ">=18" }

A start script and engine version help hosting platforms run your app correctly.

Example 2 (javascript)
pm2 start server.js --name my-app
pm2 status
Output
โ”Œโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ id โ”‚ name     โ”‚ status  โ”‚
โ”‚ 0  โ”‚ my-app   โ”‚ online  โ”‚

PM2 keeps the app running and restarts it automatically on crashes.

Key points

  • Deployment makes your app publicly accessible.
  • Use environment variables for configuration, never hardcode secrets.
  • A 'start' script in package.json tells platforms how to run your app.
  • Process managers like PM2 improve reliability in production.
๐Ÿ’ก Note: Popular beginner-friendly hosts include Render, Railway, and Vercel (for serverless functions).

๐Ÿ“ Quick Quiz

1. What script does most hosting platforms look for to start a Node.js app?

2. What does a process manager like PM2 provide?

3. Where should secrets be configured in production?