Dockerize the NodeJs (local)

Dockerize the NodeJs (local)

??

In this post, let's explore how to dockerize a Node.js application on a local machine.

Contents

  1. Install Docker
  2. Start NodeJs App
  3. Dockerize the NodeJs app?
  4. Start the service
  5. Check the status of the image



Install docker:

  • You can go ahead and download and install the appropriate Docker package on your local system.
  • For Windows, we can install the docker desktop.
  • To make sure the installation is done, run this command, it’ll return the installed docker version.
  • Open the docker desktop, and initiate the docker.


Initiate Simple NodeJs App

  • Initiate the package.json
  • Install the express
  • Create a simple app

const express = require('express')
const app = express()
const port = 3000

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})        

Dockerize the NodeJs app?

  • Create the docker file - Dockerfile

FROM node:19-alpine

COPY package.json   /app/
COPY app.js /app/
 
WORKDIR /app

RUN npm install

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

        

  • From: - Create a container from this base image. For example, if this is a Java application, it should start with Tomcat
  • COPY - copy the required files to start the application.
  • WORKDIR - app working directory to run the commands
  • RUN - to run the commands inside the container
  • CMD - commands to execute to start the app.


Build Image

  • Build the docker image
  • Run this docker command in the app path

docker build -t docker-app.        
Docker build command

  • Build - build the docker image
  • -t - with image name
  • docker-app - image name
  • . path of the docker file
  • After this command, check the docker images


docker images

Run the Image

  • Run the docker images using the following command

docker run -d -p 3000:9000 docker-app:latest        

  • docker run - to run the image
  • -d - to run the container in background mode
  • -p - to open a port connection between the app host and the container.?
  • <Host port> :< App port in the Container>
  • Image name with tag
  • To check the docker image status

docker ps        
docker ps

Output



To delete the container,

  • Stop the container by using the Container ID

docker stop <Container ID>
docker rm <Container ID>        

Thanks

Balaji Murali

Lead Test engineer / Game Design (iGaming)

7 个月

Very helpful!

回复

要查看或添加评论,请登录

Nanthakumar D的更多文章

社区洞察

其他会员也浏览了