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.
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.
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
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"]
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! 🎉
Let's break down what we did:
The -p 3000:3000 flag maps port 3000 from the container to port 3000 on your machine.
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