Deploying a Node.js Express App with Docker

Home » Programming » Deploying a Node.js Express App with Docker
Deploying a Simple Node.js Express App with Docker

Deploying a Node.js Express App with Docker

Docker simplifies the process to deploy a Node.js Express app by packaging it into a container. In this guide, we’ll show how to deploy deploy a Node.js Express app step-by-step using Docker.

Prerequisites:

 

Step 1: Create the Node.js Express App

First, initialize a basic Express app. If you haven’t already, install Node.js and npm. Then, follow these steps:

mkdir node-docker-app
cd node-docker-app
npm init -y
npm install express

 

Next, create an app.js file:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, Docker!');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`App running on port ${PORT}`);
});

 

Step 2: Create a Dockerfile

A Dockerfile is essential for building your Docker image. Create a Dockerfile in the project root:

# Use the official Node.js image
FROM node:14

# Set the working directory
WORKDIR /usr/src/app

# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install

# Copy the rest of the application code
COPY . .

# Expose the application port
EXPOSE 3000

# Start the app
CMD ["node", "app.js"]

 

Step 3: Build and Run the Docker Container

Once the Dockerfile is set up, you can build and run the container:

docker build -t node-docker-app .
docker run -p 3000:3000 node-docker-app

Now, your Node.js app will run in a Docker container, and you can access it by navigating to http://localhost:3000.

 

Conclusion:

Deploying a Node.js Express app with Docker simplifies the deployment process. This setup ensures your app runs the same way in any environment. Consequently, this method is ideal for development and production environments alike!