How to setup Node.Js with MongoDB using Docker

How to setup Node.Js with MongoDB using Docker

Docker Overview

Docker is an open platform for developing, running, and shipping apps. Docker allows you to separate your apps from your architecture so that you can deliver the software faster. With Docker, you can manage your infrastructure the same way you manage your apps. By taking advantage of Docker’s methodology for dispatching, testing, and uploading code faster on the server, you can significantly reduce the delay between writing code and running it to production.

Docker includes the components like Docker client, Docker server, Docker machine, Docker hub, Docker composes, etc.

Docker Containers Vs. Virtual Machine

Docker Containers

Virtual Machine

Integration in a container is quick and cheap. Virtual integration is slow and expensive.
No memory wastage. Memory wasting.
It uses the same kernel, but with a different distribution. It uses many independent operating systems.

Why Docker?

Docker is designed to benefit both the Developer and the System Administrator. There are the following reasons for using Docker – 

  • Docker allows us to easily install and run the software without having to worry about setting up or dependencies.
  • Developers use Docker to remove machine problems like code working on some developer’s machine and not working on another’s machine when working with the team.
  • Operators use Docker to run and manage applications on remote containers for optimal computer density.
  • Enterprises choose Docker for agile software delivery pipelines to deliver new app features more quickly and securely.

Advantages of Docker

Docker has the following advantages –

  • Executes the container in seconds instead of minutes.
  • Uses less memоry.
  • Prоvides lightweight virtuаlizаtiоn.
  • Applications do not require a complete operating system to run.
  • Uses app dependencies to minimize risk.
  • Docker lets you use remote repositories to share your container with others.
  • Provides constant deployment and testing environment.

Disadvantages of Docker

Docker has the following disadvantages –

  • Increases the complexity due to the extra layer.
  • It is difficult to handle a large number of containers.
  • Docker lacks some features such as container self-registration, container self-inspection, copying of files hosted in the container, and more.
  • Docker is not a good solution for apps that require a rich graphical interface.
  • Docker has a cross-platform compatibility option means that if the app is designed to run in a Docker container on Windows, then it will not work on Linux or vice versa.

Hire nodejs developers india

Dосker Architecture

Docker follows the client-server architecture, consisting of three key components: the Docker client, the Docker host, and the Docker registry.

  • Dосker Сlient
    • Commands and REST APIs are used by the docker client to communicate with the Docker daemon (server). Docker clients allow the user to interact with docker.
  • Dосker Hоst
    • The Docker Host is used to provide the environment for applications to run and execute. This includes the Docker daemon, images, containers, networks, and storage. It also communicates with other daemons to manage its services.
  • Dосker Registry
    • Docker registries are services that provide a location, from where you can download and store images.

Getting started with Docker

We check out the basics to get started with Docker. The parts include:

  • Part 1: Install Docker in your machine.
  • Part 2: Setup simple node js application.
  • Part 3. Create Dockerfile for app.
  • Part 4: Write Docker Compose configurations.
  • Part 5: Mongoose models.
  • Part 6: MongoDB database connection.
  • Part 7: Create API for getting and storing users.
  • Part 8: Run docker-compose to build the application.
  • Part 9: Important Docker commands.

Part 1: Install docker in your machine(ubuntu)

  • Set up the repository:
    •  Update apt package index using:
      • sudo apt-get update
    • Install packages that allow apt  to use a repository over HTTPS:
      •  sudo apt-get install ca-certificates curl gnupg lsb-release
    • Add Docker’s official GPG key:
      • curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg –dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    • Set up the stable repository:
      • echo “deb [arch=$(dpkg –print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] download docker $(lsb_release -cs) stable” | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
  • Install Docker Engine
    • Update apt package index using: sudo apt-get update
    • Install the latest version of Docker Engine and containers: sudo apt-get install docker- ce docker-ce-cli containerd.io
    • Verify Docker Engine is installed correctly by running the hello-world image: sudo docker run hello-world.

Part 2: Set up the Simple NodeJS Application

Let’s set up a node app without a docker.

  • Create a node app with the following command
    • npx express-generator
  • Install the node packages
    • npm install
  • Run the app
    • npm start

In the next steps, we will see how you can run this app in a Docker container using the official docker image. First, you need to create a docker image for your application.

Part 3: Create a Docker File for the App

In the example above we have seen how the project is created and how the application is tuned simply. Let us see how to create a Dockerfile and run the same application in Docker.

At the root of the project directory, we are going to create a Dockerfile.

We need to create a docker file that will create the Docker image. Here is the file that starts with the FROM command and the base image node: 8.11-Slim. We are using the /usr/src/app as a WORKDIR and copying package.json before installing dependencies. By doing this step first makes you not install these dependencies every time you change any files.

Now final “Dockerfile” look like this:

docker file

Let me explain some points:

  • FROM: Install an image of the Node.js version.
  • WORKDIR: Define the path to the working directory.
  • COPY: Copy the package.json file into the container, and then the second copy all the files within the project directory.
  • RUN: Run a command-line inside the container: npm install to install all dependencies in package.json.
  • CMD: Once the image is created, run the script npm start.
  • EXPOSE: You can tell docker that the container listening to which ports at runtime.

Part 4: Write Docker compose configuration

At the root of the project directory, we are going to create the docker-compose.yml file. Follow the syntax of version 3 described by Docker:

Your docker-compose.yml should now look something like this:

docker compose

Let me explain some points:

  • image: Official Docker image.
  • restart: Configure restart policy.
  • env_file: Specify our .env path which we will create later.
  • container_name: Specify a custom container name instead of the one created by default.
  • ports: The specified ports are used.
  • volumes: Map volume folder.

Now use the command to run the entire setup in development mode to monitor the container:

  • Build with no-cache
    • docker-compose build –no-cache
  • Start the services(Check on your browser http://localhost:5500)
    • docker-compose up
  • List the services
    • docker-compose ps
  • List the containers
    • docker ps
  • Stop services
    • docker-compose stop

Part 5: Mongoose Models

We can create a dedicated ‘models/user.js‘ directory to store our mongoose model and we’ll start with a user.js file. The model describes only two field names and the city of the users.

user.js will contain this code.

Mongoose Models

Part 6: MongoDB database connection

Create a file that exists in ‘midddleware/database.js‘.
Here we have created a database name as docker-db.

MongoDB Database Connection

Part 7: Create API for get and store users

  • 1. Store New User To MongoDB
    • We are getting the data from the postman we have to do something with it. We want to store user data in the database. We will make use of the user.js model we had created earlier.
      Now we can add ‘/store’ route in ‘routes/users.js’ file which will use to create a new user in the MongoDB database.
    • Api
    • Now we can add the /store API like so.
    • api stored
    • That should be enough to store a new user into the database.
    • We get the result like this.
    • output
  • 2. Displaying users from the database:
    • This API is used to get all users which we have created in the database.
    • Now we can add the /get like so.
    • user from database
    • We get the result like this.

    • output2
    • The final ‘routes/user.js’ file look like this:
    • Final routes

Part 8: Run docker-compose to build the application

  • Start the application by running the following command.
    • docker-compose up
  • Our application should be running at ‘http://localhost:5500/’.
  • And check Mongo-express UI on ‘http://localhost:8083/’

Part 9: Important docker commands

  • 1. docker images (check all available docker images)
  • 2. docker run redis (run particular docker image, it ready to accept connections)
  • 3. docker ps (Check running docker image)
  • 4. docker run -d redis (running docker image in detach mode)
  • 5. docker stop id_of_image (To stop detach mode running image)
  • 6. docker start id_of_image (start existing image)
  • 7. docker ps -a (list all connection images )
  • 8. docker run -p3000:6379 redis (change running port 6379 to 3000)
  • 9. docker logs id/names
  • 10. docker run -d -p3000:6379 redis (Use when creating new container only)
  • 11. docker start id (Use when we want to run existing container)
  • 12. docker network ls (provide a list of all available networks)
  • Connection commands:
  • 13. docker network create mongo-network (create a new network)
  • 14. docker run -p 27017:27017 -d -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=password –name mongodb –net mongo-network mongo (Run mongo image)
  • 15. docker logs generated_id (check a log of newly created connection)
  • 16. docker run -d -p 8081:8081 -e ME_CONFIG_MONGODB_ADMINUSERNAME=admin -e ME_CONFIG_MONGODB_ADMINPASSWORD=password –net mongo-network –name mongo-express -e ME_CONFIG_MONGODB_SERVER=mongodb mongo-express (Run mongo-express image)
  • 17. docker logs id -f (for running log screen)
  • 18. docker-compose -f docker-compose.yaml up ( instead of command no. 14 ) (If there is no running connection then it creates default one)
  • 19. docker-compose -f docker-compose.yaml down ( instead of command 5)
  • 20. docker rmi id (Use to delete image)
  • 21. docker rm id (Use to delete container)22. docker exec -it id /bin/sh (Use for the interactive terminal of logs)
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *