All blog posts

Containerizing a Node.js App with Docker: A Beginner's Guide

Hey there! I'm going to walk you through how to containerize a Node.js application using Docker. Let's break it down into a few steps.

What is Docker and Why Should You Care?

Before we dive in, let's quickly cover what Docker is. Think of Docker as a way to package your entire application, including all its dependencies, into a single "container" that can run consistently anywhere. It's like creating an isolated environment for your app that works the same way on your laptop, your coworker's computer, or a server in the cloud.

Prerequisites

  • Node.js installed on your computer
  • Docker Desktop installed
  • A simple Node.js application (we'll use a basic Express app as an example)

1. Creating a Simple Node.js App

First, let's create a super basic Node.js app. Make a new directory and initialize it:

mkdir docker-nodejs-demo
cd docker-nodejs-demo
npm init -y

Now create an index.js file:

const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Hello from my containerized app! 🐳");
});

app.listen(port, () => {
  console.log(`App running on http://localhost:${port}`);
});

Don't forget to install Express:

npm install express

2. Creating the Dockerfile

Here's the important bit: create a file named Dockerfile (no extension) in your project root:

# Start from Node.js base image
FROM node:18

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy app source code
COPY . .

# Expose port
EXPOSE 3000

# Start command
CMD ["node", "index.js"]

3. Building and Running the Container

Time to build our container! Run these commands:

# Build the image
docker build -t my-nodejs-app .

# Run the container
docker run -p 3000:3000 my-nodejs-app

Visit http://localhost:3000 in your browser, and you should see your app running! 🎉

What Just Happened?

Let's break down what we did:

  1. Created a basic Express app
  2. Wrote a Dockerfile with instructions for building our container
  3. Built a Docker image from our Dockerfile
  4. Ran a container from that image

The -p 3000:3000 flag maps port 3000 from the container to port 3000 on your machine.

Bonus Tips!

  • Use .dockerignore to exclude node_modules and other unnecessary files
  • For production, consider using multi-stage builds
  • Always specify a Node.js version instead of using latest

Next Steps

Try modifying the app and rebuilding the container. Play around with different Docker commands like docker ps to see running containers or docker images to list your images.

All blog posts