Learn Express.js · 14/14

Deployment and Process Management

10 min read

You have spent weeks building your Express.js API. It works flawlessly on your computer. You run node server.js, open your browser to http://localhost:3000, and smile. But localhost is just your machine. Right now, if you close your laptop, your application ceases to exist.

To share your application with the world, you must deploy it. Deployment is the act of moving your application from your local development environment to a remote server that runs 24/7. However, running an app in the wild internet is vastly different from running it on your laptop.

Let us explore how the industry prepares, manages, and ships Express applications.


1. Preparing Your Express App for Production (NODE_ENV)

The Problem

During development, your application needs to be chatty. If a bug occurs, you want your server to print a massive, detailed stack trace on the screen so you know exactly which line of code failed. You also want your server to constantly read files fresh from the disk in case you changed them.

If you put this exact same behavior on a live internet server, you face two massive problems:

  1. Performance: Reading files fresh on every single request is incredibly slow.
  2. Security: If an attacker intentionally triggers an error, your "helpful" development stack trace will print out your folder structures, library versions, and potentially sensitive variables right on their screen.

The Definition

NODE_ENV is an environment variable used in Node.js applications to specify the environment in which an application is running (usually development or production).

The Solution

By explicitly setting the NODE_ENV variable to production, you tell Express.js and your other dependencies that the app is now live. Express acts differently when it sees this variable. It automatically:

  • Caches view templates (if you are using things like Pug or EJS).
  • Caches CSS extensions.
  • Generates less verbose error messages (hiding stack traces from users).

Just by flipping this one switch, your Express app can become up to three times faster.

The Real-Life Simulation

Imagine a theater play. development mode is the rehearsal. If an actor forgets a line, the director stops the play, walks on stage, and loudly explains the mistake in front of everyone. production mode is opening night. If an actor forgets a line, they improvise, keep the show moving, and the audience never sees the internal chaos.

Industry Practice: How to Set It

In the industry, we never hardcode this in our JavaScript. We pass it through the environment.

Locally for testing (Linux/macOS):

bash
export NODE_ENV=production
node app.js

Locally for testing (Windows PowerShell):

powershell
$env:NODE_ENV="production"
node app.js

Inside your Express code, you can check it if you need to run specific logic (like connecting to a production database vs a local one):

javascript
const express = require('express');
const app = express();

// Express automatically reads process.env.NODE_ENV under the hood to optimize itself,
// but you can also use it for your own logic:
if (process.env.NODE_ENV === 'production') {
  console.log('Running in production mode: Stack traces are hidden.');
} else {
  console.log('Running in development mode: Debugging is enabled.');
}

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000);

2. Keeping Your App Alive: Process Management with PM2

The Problem

When you run your app using node app.js, that process is tied directly to your terminal session. If you close the terminal, the app dies. Worse, Node.js runs on a single thread. If a single unexpected error throws an exception that you forgot to catch, the entire Node.js process crashes, and your server goes offline until you manually restart it.

The Definition

PM2 (Process Manager 2) is a production process manager for Node.js applications that includes a built-in load balancer. It runs in the background as a daemon and manages your application processes.

The Solution

PM2 solves the crashing issue by watching your application. If your Express app crashes because of a bug, PM2 instantly restarts it. It also detaches the process from your terminal, meaning it runs silently in the background of your server indefinitely. Furthermore, it can utilize all the CPU cores on your server by running multiple instances of your app simultaneously.

The Real-Life Simulation

Imagine a 24/7 drive-thru window. The cashier (your Express app) handles customer orders. In a node app.js world, if the cashier faints from exhaustion, the drive-thru stops completely until the manager drives to the store to wake them up. In a PM2 world, PM2 is a robotic claw on the ceiling. The absolute millisecond the cashier faints, the claw sweeps them away and drops a fresh, fully awake clone into the booth. The next car in line barely notices a delay.

Industry Practice: How to Use PM2

We only use PM2 on traditional servers (like Virtual Private Servers from DigitalOcean or AWS EC2). We do not usually use PM2 inside Docker or serverless environments.

1. Installation:
Install it globally on your server so it can manage all apps.

bash
npm install pm2 -g

2. Starting your app:
Instead of node app.js, you tell PM2 to start it and give it a recognizable name.

bash
pm2 start app.js --name "my-express-api"

3. Useful Commands:
Industry engineers use these daily to monitor server health:

bash
# See all running applications and their memory/CPU usage
pm2 list

# View the live logs (console.logs and errors) of your apps
pm2 logs

# Restart the app (useful after pulling new code from GitHub)
pm2 restart my-express-api

# Stop the app
pm2 stop my-express-api

4. The "Survive a Server Reboot" trick:
If the physical server loses power and restarts, PM2 needs to know how to start itself back up.

bash
pm2 startup
# (Run the command that PM2 spits out in the terminal)
pm2 save

pm2 save literally saves the current list of running apps so they are booted back up automatically if the machine restarts.


3. Containerizing Your Express Application with Docker

The Problem

The most common phrase in software engineering is: "It works on my machine!"
You build an Express app on your MacBook using Node.js version 20. You send the code to a production server running Ubuntu Linux with Node.js version 16. Suddenly, functions are failing, file paths are broken, and native C++ modules inside your node_modules refuse to compile. Your application environment is heavily dependent on the host operating system.

The Definition

Docker is a software platform that utilizes OS-level virtualization to deliver software in standardized packages called containers. A container holds the application code, libraries, system tools, and runtime needed to run the software.

The Solution

Docker packages your Express application entirely into a self-contained box (a container). This box includes its own tiny Linux operating system and the exact version of Node.js you want. When you move this box to a cloud server, it doesn't care what operating system the server is running. Docker acts as a translator, guaranteeing that the app will run exactly identical to how it ran on your laptop.

The Real-Life Simulation

Imagine moving to a new country. Usually, you have to pack all your furniture, ship it, and then hope it fits into the uniquely shaped rooms of your new house, praying their electrical outlets match your appliances. Docker is like taking your entire current living room—the walls, the floor, the furniture, and the electricity—shrinking it down into an indestructible steel box, and dropping it onto an empty field in the new country. The inside of the room never changed.

Industry Practice: The Standard Dockerfile

To tell Docker how to build this box, you create a file named exactly Dockerfile (no extension) in the root of your project.

Here is the minimalistic, industry-standard Dockerfile for an Express app:

dockerfile
# 1. Start from a tiny, specific version of Node.js (Alpine Linux is heavily used for small sizes)
FROM node:20-alpine

# 2. Set the working directory inside the container
WORKDIR /app

# 3. Copy ONLY package files first. 
# (This is a caching trick. If you don't change dependencies, Docker skips reinstalling them!)
COPY package*.json ./

# 4. Install dependencies. 
# 'npm ci' is strict, and '--omit=dev' ensures we don't install heavy testing/formatting tools in production.
RUN npm ci --omit=dev

# 5. Copy the rest of your application code into the container
COPY . .

# 6. Document which port the container should expose
EXPOSE 3000

# 7. The command to run when the container starts
CMD ["node", "app.js"]

Wait, what about node_modules?
You never want to copy your local node_modules into the container. Add a .dockerignore file (just like .gitignore) to your project root:

text
node_modules
npm-debug.log
.env

To build and run this container locally:

bash
# Build the image (the blueprint) and tag it with a name
docker build -t my-express-app .

# Run the container from the image, mapping your computer's port 3000 to the container's port 3000
docker run -p 3000:3000 -d my-express-app

4. Deploying to Cloud Platforms (Render, AWS, or DigitalOcean)

The Problem

You have prepared your code for production, and you have either a robust PM2 setup or a neat Docker container. But right now, it is still sitting on your hard drive. How do you give it a public IP address and a URL so your users can access it?

The Definition

Cloud Platforms are companies that rent out computing resources (servers, databases, network infrastructure) over the internet.

The Solution

You push your code to a Cloud Platform. There are three main tiers of cloud hosting in the industry:

  1. PaaS (Platform as a Service) - e.g., Render, Heroku:

    • How it works: You just give them your GitHub repository. They handle the server, the OS, the networking, and the SSL certificates automatically.
    • Industry use: Startups, MVP (Minimum Viable Products), and internal tools. Extremely fast to set up, but more expensive at a high scale.
  2. IaaS (Infrastructure as a Service) - e.g., DigitalOcean Droplets, AWS EC2:

    • How it works: They give you a blank Linux computer in the cloud. You must SSH into it, install Node.js, install PM2, configure firewalls, and route traffic yourself.
    • Industry use: Medium-to-large companies that need custom configurations and cheaper scaling.
  3. CaaS (Container as a Service) / Serverless - e.g., AWS Fargate, Google Cloud Run:

    • How it works: You give them your Docker container. They run it for you, spinning up 100 copies if traffic spikes, and spinning down to 0 copies if no one is visiting (saving you money).
    • Industry use: Massive enterprise architectures.

Industry Practice: Deploying to Render

Render is currently one of the most popular and developer-friendly PaaS providers. It is heavily used in the industry to get an Express API up and running in minutes.

Steps to deploy an Express app on Render:

  1. Push your Express code to a public or private GitHub repository.
  2. Log into Render.com and click New+ -> Web Service.
  3. Connect your GitHub account and select your repository.
  4. Render will ask you for a few settings:
    • Environment: Node (or Docker if you are using your Dockerfile).
    • Build Command: npm install (Render runs this to prepare your app).
    • Start Command: node app.js (Render runs this to start the server).
  5. Scroll down to Environment Variables and add NODE_ENV with the value production.
  6. Click Create Web Service.

Render will provision a server, download your code, run the build command, and start your app. Within 2 minutes, you will be handed a shiny new URL (e.g., https://my-express-api.onrender.com).

Your Express application is now officially alive on the internet. 🎉


References & Extra Reading

To deepen your understanding of these tools, always go straight to the creators' documentation:

Challenge

You are tasked with preparing an Express.js application for deployment using Docker. Your application's main entry point is server.js, and it listens on port 3000.

Your goal is to write a complete, production-optimized Dockerfile and the contents of a corresponding .dockerignore file.

Dockerfile Requirements:

  1. Start from the official node:18-alpine base image.
  2. Set the container's working directory to /usr/src/app.
  3. Copy the package.json and package-lock.json files into the working directory.
  4. Install only the production dependencies using the most efficient npm command for CI/CD environments.
  5. Copy the rest of the application source code into the container.
  6. Set the NODE_ENV environment variable to production inside the image.
  7. Expose port 3000 to allow traffic to the application.
  8. Define the default command to run the application using node.

.dockerignore Requirements:

Write the contents of the .dockerignore file that prevents the node_modules directory and any .env files from being copied into the container image.

Combine both parts in the editor. First, write the complete Dockerfile. Then, add a separator like ### .dockerignore ### and write the contents of the .dockerignore file below it.

Expected result

The output should be a single block of text containing a valid Dockerfile followed by the contents of a .dockerignore file, separated by ### .dockerignore ###.

Example Structure:

dockerfile
# Dockerfile content adhering to all requirements
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "server.js"]

### .dockerignore ###
node_modules
.env

The Dockerfile must correctly use instructions like FROM, WORKDIR, COPY, RUN, ENV, EXPOSE, and CMD. The COPY and RUN steps for dependencies must be ordered correctly to leverage Docker's layer caching. The npm command must be npm ci --omit=dev for production optimization. The .dockerignore section must contain the specified patterns.

dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.