Dockerizing a Node.js Application

Dockerizing a Node.js Application

  1. Check if the node.js Application is running locally.

  2. Remove the node_modules folder. (not necessary but then this directory will be excluded in further steps)

  3. Create a file named Dockerfile in the same directory as index.js (it can be done using vs code, create a new file, or by using the touch command ie. touch Dockerfile).

    Docker can build images automatically by reading the instructions from a Dockerfile

  4. Paste these lines in this Docker file

     FROM node:slim
     WORKDIR /app
     COPY . /app
     RUN npm install
     EXPOSE 3000
     CMD node index.js
    
    1. FROM node: slim -> Our Docker image will be built on top of Node.js image named slim.

    2. WORKDIR /app -> It will use a directory named app to create the image.

    3. COPY . /app -> copy all the contents of the current directory in the app directory.

    4. RUN npm install -> initial setup command to install all the packages and modules.

    5. EXPOSE 3000 -> The docker image will use this port inside that container.

    6. CMD node index.js -> This command will start the Node.js app.

  5. Run this command in the terminal in the same directory

    1. -t stands for the tag to provide a particular name to the image.

    2. adixit7386 is the username in the Dockerhub

  6. Run this command in the terminal to run this image

    -d stands for detached mode

    -p will expose the port of the os to the port of container

  7. The container will be visible in the Docker Desktop

  8. Now we can push the image to Dockerhub using this command