Learn Node.js Β· 13/13

Production Ready: Deployment and DevOps Basics

8 min read

Production Ready: Deployment and DevOps Basics πŸš€

Welcome, intrepid Node.js developer! You've wrestled with asynchronous code, wrangled databases, and built a masterpiece. But now what? It's time to release your creation into the wild, the glorious realm of "production." This guide will be your trusty compass, navigating you through the essential practices to get your Node.js application deployed and running smoothly.


1. Managing Secrets: Environment Variables (.env) for Production 🀫

The Problem: Your application likely has sensitive information: database passwords, API keys, and other secret credentials. Hardcoding these directly into your source code is like leaving your house keys under the doormat – a terrible idea. If you push your code to a public repository (like GitHub), you've just given away the keys to your kingdom.

The Solution: Environment Variables

Environment variables are variables that live outside of your application's code and are injected into the application's environment at runtime. This allows you to keep your sensitive data separate from your codebase.

A common and convenient way to manage these variables during development is by using a .env file. This is a simple text file where you can store your secrets in a KEY=VALUE format.

Getting Started with .env and dotenv

The dotenv package is a popular choice for loading environment variables from a .env file into process.env in your Node.js application.

Installation:

bash
npm install dotenv

Usage:

  1. Create a .env file in the root of your project:

    ini
    DB_HOST=localhost
    DB_USER=root
    DB_PASS=s1mpl3p@ssw0rd
    API_KEY=your_super_secret_api_key
  2. Load the variables in your application's entry file (e.g., index.js or app.js) as early as possible:

    javascript
    require('dotenv').config();
    
    const dbHost = process.env.DB_HOST;
    const dbUser = process.env.DB_USER;
    // ... and so on

🚨 Important Security Note: NEVER commit your .env file to version control. Add it to your .gitignore file immediately:

asciidoc
.env

Interesting Fact: The concept of separating configuration from code is one of the principles of the "Twelve-Factor App" methodology, a set of best practices for building modern, scalable applications.


2. Process Management: Keeping Apps Alive with PM2 πŸ”„

The Problem: So, you've deployed your app and started it with node app.js. What happens if your application crashes due to an unhandled error? It goes down, and stays down, until you manually restart it. This is not ideal for a production application that needs to be available 24/7.

The Solution: A Process Manager

A process manager is a tool that helps you manage and daemonize your applications (run them in the background as a service). PM2 is a popular and powerful process manager for Node.js. It provides features like:

  • Automatic Restarts: If your app crashes, PM2 will automatically restart it.
  • Clustering: It can run your application in cluster mode, taking advantage of all available CPU cores.
  • Log Management: PM2 aggregates and manages your application's logs.
  • Monitoring: It provides a dashboard to monitor your application's resource usage.

Getting Started with PM2

Installation:

bash
npm install pm2 -g

Starting Your Application:

bash
pm2 start app.js

Common PM2 Commands:

  • pm2 list or pm2 ls: Lists all running processes.
  • pm2 stop <app_name|id>: Stops a specific application.
  • pm2 restart <app_name|id>: Restarts a specific application.
  • pm2 delete <app_name|id>: Stops and removes an application from PM2's list.
  • pm2 logs: Displays the logs for all applications.

Ensuring Uptime with a Startup Script:

To make sure your applications restart automatically after a server reboot, you can generate a startup script:

bash
pm2 startup

This command will provide you with a command to run, which will configure PM2 to start on system boot.

Funny Exaggeration: Without a process manager, your server is like a dramatic actor who faints at the slightest inconvenience and needs to be revived with smelling salts (your manual intervention). With PM2, it's more like a relentless action hero who gets knocked down but always gets back up.


3. Containerization: Writing Your First Dockerfile for Node 🐳

The Problem: "It works on my machine!" – a phrase that has echoed through the halls of software development for decades. Differences in operating systems, installed libraries, and configurations between your development environment and the production server can lead to unexpected bugs.

The Solution: Containerization with Docker

Docker allows you to package your application and all its dependencies into a standardized unit called a container. This container can then run on any machine that has Docker installed, ensuring a consistent environment from development to production.

At the heart of building a Docker image is the Dockerfile, a text file that contains a series of instructions on how to build the image.

A Simple Dockerfile for a Node.js App:

dockerfile
# Use an official Node.js runtime as a parent image
FROM node:18-alpine

# Set the working directory in the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install app dependencies
RUN npm install

# Bundle app source
COPY . .

# Your app binds to port 3000, so you need to expose it
EXPOSE 3000

# Define the command to run your app
CMD [ "node", "app.js" ]

Breakdown of the Dockerfile:

  • FROM node:18-alpine: This specifies the base image to use. The alpine version is a lightweight Linux distribution, which results in a smaller final image.
  • WORKDIR /usr/src/app: Sets the working directory inside the container.
  • COPY package*.json ./: Copies the package.json and package-lock.json files.
  • RUN npm install: Installs the project's dependencies.
  • COPY . .: Copies the rest of your application's source code into the container.
  • EXPOSE 3000: Informs Docker that the container listens on port 3000.
  • CMD [ "node", "app.js" ]: Specifies the command to run when the container starts. It's recommended to use the node command directly instead of npm start for better signal handling.

Building and Running the Docker Image:

  1. Build the image:

    bash
    docker build -t my-node-app .
  2. Run the container:

    bash
    docker run -p 3000:3000 my-node-app

This will run your containerized Node.js application and map port 3000 on your host machine to port 3000 in the container.

Industry Practice: For production, it's common to use multi-stage builds to create smaller and more secure images. A multi-stage build allows you to use one image for building your application (with development dependencies) and another, leaner image for running it in production.


4. Going Live: Deploying to Cloud Platforms (Render/AWS) ☁️

Now that you have your application containerized, it's time to deploy it to the cloud. There are many cloud platforms available, each with its own strengths. We'll look at two popular options: Render (for its simplicity) and AWS (for its power and flexibility).

Deploying to Render

Render is a unified cloud platform that makes it incredibly easy to deploy web applications, APIs, and databases.

Steps to Deploy on Render:

  1. Sign up for a Render account and connect your GitHub, GitLab, or Bitbucket account.
  2. Create a New Web Service: From your dashboard, click "New" and then "Web Service".
  3. Connect Your Repository: Choose the repository containing your Node.js application.
  4. Configure Your Service:
    • Name: Give your service a unique name.
    • Environment: Select "Node".
    • Build Command: npm install (or yarn).
    • Start Command: node app.js.
  5. Add Environment Variables: Under the "Environment" tab, you can add your secret keys and other environment variables from your .env file.
  6. Deploy: Click "Create Web Service". Render will automatically build and deploy your application.

Render also offers features like automatic deploys on every push to your repository and free TLS certificates.

Deploying to AWS (Elastic Beanstalk)

Amazon Web Services (AWS) is a comprehensive cloud platform. AWS Elastic Beanstalk is a service that makes it easier to deploy and scale web applications.

Steps to Deploy on AWS Elastic Beanstalk:

  1. Create an AWS Account: If you don't have one, you'll need to create an AWS account.
  2. Create an Elastic Beanstalk Application: In the AWS Management Console, navigate to Elastic Beanstalk and click "Create Application".
  3. Configure the Environment:
    • Application name: Choose a name for your application.
    • Platform: Select "Node.js".
    • Application code: You can upload your code as a ZIP file. Before zipping, make sure to exclude the node_modules directory.
  4. Create Application: Click "Create application". Elastic Beanstalk will provision the necessary resources (like EC2 instances) and deploy your code.
  5. Configure Environment Variables: In your environment's configuration, you can set the environment variables your application needs.

This is a simplified overview. AWS offers a vast array of services, and a production deployment can involve setting up databases (RDS), load balancers, and more.

Humorous Analogy: Deploying to Render is like ordering a pre-made meal kit – everything is conveniently packaged for you. Deploying to AWS is like going to a massive grocery store with every ingredient imaginable, giving you the power to cook anything you want, but also requiring you to know the recipe.


Extra Reading & References πŸ“š

Challenge

You are tasked with creating a Dockerfile to containerize a production-ready Node.js web application. The application's source code includes a server.js file, package.json, and package-lock.json.

Your Dockerfile must perform the following actions in the specified order:

  1. Start from the official node base image with the 18-alpine tag.
  2. Set the container's working directory to /app.
  3. Copy package.json and package-lock.json into the working directory.
  4. Execute the command to install production dependencies using a clean install method (npm ci).
  5. Copy all the remaining application files from the host to the container's working directory.
  6. Inform Docker that the container will listen on port 3000 at runtime.
  7. Define the default command to execute when the container starts, which should run the application using node server.js.

Expected result

Your Dockerfile should contain the following instructions in the correct order to build a valid Docker image for the Node.js application as described.

dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./

RUN npm ci --only=production

COPY . .

EXPOSE 3000

CMD ["node", "server.js"]
dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.