Header Ads

Deploy Node.js Apps with Docker and Docker Compose

 Step-by-Step Guide to Deploying Node.js Applications with Docker and Docker Compose

Deploying Node.js apps with Docker ensures consistency across development, staging, and production environments. By using Docker Compose, you can manage multi-container setups with ease. This guide walks you through creating a Dockerized Node.js backend and deploying it for scalable, reliable operations.



Why Use Docker for Node.js?

  • Environment Consistency – No more “it works on my machine” issues.
  • Scalability – Easily spin up multiple containers to handle increased load.
  • Simplified Deployment – Package your app with all its dependencies into one unit.
  • Portability – Run anywhere Docker is supported: servers, VMs, or cloud platforms.


Step 1: Prepare Your Node.js Application

Ensure your Node.js project has a valid package.json and entry point (index.js or server.js).
Example server.js:

const express = require('express');

const app = express();


app.get('/', (req, res) => {

  res.send('Hello Dockerized Node.js App !');

});


app.listen(7000, () => console.log('Server running on port 7000'));


Step 2: Create a Dockerfile

In the root of your project, create a Dockerfile:

# Use official Node.js image

FROM node:18


# Set working directory

WORKDIR /usr/src/app


# Copy package files and install dependencies

COPY package*.json ./

RUN npm install --production


# Copy all source code

COPY . .


# Expose app port

EXPOSE 7000


# Run the app

CMD ["node", "server.js"]


Step 3: Create Docker Compose File

Create docker-compose.yml In your project root: 

 version: '3'

services:

  app:

    build: .

    ports:

      - "7000:7000"

    environment:

      NODE_ENV: production

    restart: always


Step 4: Build and Run Containers

Build and start your container:

docker-compose up --build -d

Check logs:

docker-compose logs -f

Access your app in a browser at:

http://localhost:7000


Step 5: Deploy to Production

  1. Copy your project files to your server.
  2. Install Docker & Docker Compose:
sudo apt update
sudo apt install docker.io docker-compose -y

      3. Build and run

docker-compose up -d --build


Step 6: Manage Containers

Stop containers:

docker-compose down

Restart containers:

docker-compose restart

Update images

docker-compose pull && docker-compose up -d


Conclusion

With Docker and Docker Compose, deploying your Node.js backend is consistent, scalable, and hassle-free. You’ve now packaged your app into containers that can run anywhere, from local machines to production servers. 


Related Guides

Post a Comment

0 Comments