Containerizing a Node js Application: From Source Code to Docker Image

Moving your Nodejs application from your local machine into a Docker container is one of the best ways to ensure environment consistency between the development and production.
No more "It works on my machine " excuses !!
Step 1: Prepare an Node js application
Example
// index.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.json({ message: "Hello from inside the Docker container!" });
});
app.listen(PORT, () => {
console.log(`Application is running on port ${PORT}`);
});
Update your package.json to include a start script
"scripts":{
"start":"node index.js"
}
Step 2: Create a .dockerignore File Before copying files into your docker image, we wnat to prevent unnecessary files from bloating the image.
node_modules
npm-debug.log
.git
Step 3: Write the Dockerfile
Dockerfile is a blueprint that tells Docker how to build your application image. Create file named Dockerfile in your project root:
FROM node:20-alpine
WORKDIR: /usr/src/app
COPY package*.json .
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm","start"]
Step 4: Build the Docker Image To build Dockerfile use this command
docker build -t my-node-app:1.0 .
Step 5: Run the Container
To run the Docker Image use this command
docker run -d -p 8080:3000 --name node-app-container my-node-app:1.0


