Getting Started with Docker and Node.js
Muchhal Sagar
Posted on October 16, 2024
Docker simplifies application deployment by packaging code and its dependencies into containers. In this blog, weโll walk through the steps to containerize a simple Node.js application using Docker.
Step 1: Create a Simple Node.js Application
1. Set Up the Project Directory
Create a new directory for your Node.js app:
mkdir my-node-app
cd my-node-app
2. Initialize a Node.js Application
Run the following command to create a package.json file:
npm init -y
3. Install Express
Install Express to create a simple web server:
npm install express
4. Create an app.js File
Create a file named app.js and add the following code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello, Docker!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 2: Create a Dockerfile
1. Create a Dockerfile
In the project directory, create a file named Dockerfile (no extension) and add the following content:
# Use the official Node.js image as a base
FROM node:14
# Set the working directory
WORKDIR /usr/src/app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
# Expose the application port
EXPOSE 3000
# Command to run the application
CMD ["node", "app.js"]
Step 3: Build the Docker Image
Run the following command in the terminal:
docker build -t my-node-app .
Step 4: Run the Docker Container
After building the image, run the container:
docker run -p 3000:3000 my-node-app
Now, you can access your Node.js application at http://localhost:3000.
Posted on October 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.