Project: Packaging Node.js Services with Live Reloading
In this project, we will package a Node.js API server inside a Docker container. We will configure host bind mounts and package volumes so you can edit code on your host machine and see changes reflect in the container in real-time, without rebuilding the image.
1. Project Workflow
graph TD
A[Create Node API Server] --> B[Write Dockerfile exposing port 3000]
B --> C[Configure Bind Mount for src/ code]
C --> D[Configure Anonymous Volume to protect node_modules]2. Walkthrough Guide
Step 1: Create a Basic Node.js API
Create a new directory and initialize the Node project:
mkdir node-docker-dev
cd node-docker-dev
npm init -y
npm install express
npm install --save-dev nodemonAdd a start script to your package.json file:
"scripts": {
"dev": "nodemon index.js"
}Create an index.js file:
// index.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello from inside the Docker container!');
});
app.listen(port, () => {
console.log(`API listening on port ${port}`);
});Step 2: Write the Dockerfile
Create a Dockerfile in your root directory:
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]Create a .dockerignore file to prevent copying local node modules:
node_modules
npm-debug.logStep 3: Run the Container with Live Reloading
Run the container, configuring a bind mount for your source code and an anonymous volume to protect the container's node_modules folder from being overwritten by your empty local directory:
docker run -d \
-p 3000:3000 \
--name api-dev-container \
-v $(pwd):/app \
-v /app/node_modules \
my-node-api-imageOpen index.js on your host machine, change the response text, and save the file. The server inside the container will reload automatically.
Note: On Windows PowerShell, use $(pwd) to get the current working directory.