DEV Community

Cover image for Building and Running a Node.js App with Multi-Stage Docker Builds
Muhammad Awais Zahid
Muhammad Awais Zahid

Posted on

Building and Running a Node.js App with Multi-Stage Docker Builds

Create an EC2 machine on AWS

Sign in to your AWS account, go to the EC2 dashboard and launch an instance with the following configuration.

Image description1

Image description2

Image description3

SSH using EC2 instance connect option, or MobaXterm or Putty

Image description4

Install Docker

 sudo yum update -y
 sudo yum install -y docker
 sudo service docker start
 sudo usermod -a -G docker ec2-user
Enter fullscreen mode Exit fullscreen mode

Install git

sudo yum install git -y
Enter fullscreen mode Exit fullscreen mode

Write Dockerfile

# BUILD STAGE
FROM node:18-alpine AS build

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

# DEPLOY STAGE
FROM node:18-alpine

WORKDIR /app

# ✅ Corrected line
COPY --from=build /app/dist ./dist

RUN npm install -g http-server

# EXPOSE PORT
EXPOSE 8080

CMD ["http-server", "dist", "-p", "8080", "-c-1"]

Enter fullscreen mode Exit fullscreen mode

Clone Application Source Code

git clone https://github.com/awais684/Dockerize-node.js-app.git
cp Dockerfile <repditory name>
cd <repository name>
Enter fullscreen mode Exit fullscreen mode

Build Docker image & Run container

docker build -t <image name> .
docker images
docker run -d -p 80:8080 --name cont1 <image name>
Enter fullscreen mode Exit fullscreen mode

Image description5

Image description6

Top comments (1)

Collapse
 
cowedeveloper profile image
Muhammad Owais

Great explanation!