Getting Started with Docker and Node.js

Muchhal Sagar - Oct 16 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

2. Initialize a Node.js Application

Run the following command to create a package.json file:

npm init -y
Enter fullscreen mode Exit fullscreen mode

3. Install Express

Install Express to create a simple web server:

npm install express
Enter fullscreen mode Exit fullscreen mode

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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"]

Enter fullscreen mode Exit fullscreen mode

Step 3: Build the Docker Image

Run the following command in the terminal:

docker build -t my-node-app .
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Docker Container

After building the image, run the container:

docker run -p 3000:3000 my-node-app
Enter fullscreen mode Exit fullscreen mode

Now, you can access your Node.js application at http://localhost:3000.

.
Terabox Video Player