[App development 0.5] [Node.js express Docker] Build an environment for Node.js Express MongoDB using Docker

↓ Here is a revised version of this article (a version that uses mongoose). [[App Development 1] [Node.js express Docker] Build an environment for Node.js Express MongoDB (mongoose) using Docker [December 2020]] (https://qiita.com/sho_U/items/43f6483aac8ca45a12f6)

Application development using Node.js Express MongoDB

We have decided to develop an application using Node.js Express MongoDB as a contract development. I would like to record the knowledge gained during development within a range that does not hinder it. Aside from the contents of the application, since we will develop it as a team, we will first build a development environment using Docker.

Environment to build

--Create an app container and mongodb container using docker-compose. --Save data in the test model using the connection test (mongoose) between the app container and the mongodb container. --Confirm data insertion from mongo compass --Provide authentication for mongodb. The authority of the user to create is "root", "read", "owner" --Database-like passwords are managed by environment variables (remove from git management with gitignore)

List of packages to be initially installed

 "bcrypt"
 "body-parser"
 "connect-flash"
 "cookie-parser"
 "debug"
 "ejs"
 "express"
 "express-ejs-layouts"
 "express-generator"
 "express-session"
 "express-validator"
 "http-errors"
 "http-status-codes"
 "method-override"
 "mongoose"
 "morgan"
 "nodemon"
 "passport"
 "passport-local-mongoose"

Files to prepare first

.
├── .env
├── .gitignore
├── Dockerfile
├── data
│   └── db  //Empty directory
├── docker-compose.yml
├── docker_app
│   └── Dockerfile
├── secret_file
│   ├── db.env
│   └── db_init
└── src
    ├── controllers
    │     └── initTestsController.js
    ├── models
    │     └── init_test.js
    └── package.json

.env

docker-compose build docker-compose up -d docker exec -it uniq_app_cnt bash

npx express-generator --view=ejs

paste package.json

npm install

First package to prepare

├── Dockerfile
├── data
│   └── db
├── docker-compose.yml
├── src
│   ├── node_modules
│   ├── package-lock.json
│   ├── package.json
│   └── test_db.js
├── .env
└── .gitignore

Dockerfile.


FROM node:12
WORKDIR /app
RUN npm install

docker-compose.yml


version: '3'
services:
  app:
    build: .
    container_name: <app name>_app_cnt
    ports:
      - 8080:8080
    restart: always
    working_dir: /app
    tty: true
    volumes:
      - /etc/passwd:/etc/passwd:ro
      - /etc/group:/etc/group:ro
      - ./src:/app
    command: bash
    networks:
      - <app name>-network
    depends_on:
      - mongo
  mongo:
    image: mongo:4.2.5-bionic
    container_name: <app name>_db_cnt
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
      MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
    volumes:
      - ./data/db:/data/db
    command:
      - mongod
    networks:
      - <app name>-network
networks:
  <app name>-network:
    external: true

.env.


APP_USER=hoge
MONGO_INITDB_ROOT_USERNAME=test
MONGO_INITDB_ROOT_PASSWORD=pass
MONGO_INITDB_DATABASE=testdb

.gitignore.


node_modules/
data/
.env

test_db.js


const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient

let url = 'mongodb://test:pass@mongo:27017/'
let db_name = 'testdb'
let collection_name = 'testUser'

console.log(url)
console.log(db_name)
console.log(collection_name)

const option = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
}

MongoClient.connect(url, option, (err, client) => {//mongodb connection
  if (err != null || client == null) {
    console.log("<<<log>>>fail")
    console.log(err)
  } else {
    const db = client.db(db_name)
    let rec = { "name": "Taro", "age": 30 }
    db.collection(collection_name).insertOne(rec, (err, res) => {//Insert test data
      if (err != null) {
        console.log("<<<log>>>err: insert")
        console.log(err)
        client.close()
      } else {
        db.collection(collection_name).find({}).toArray((err, result) => {//Data retrieval
          if (err != null) {
            console.log("<<<log>>>err: select")
            console.log(err)
            client.close()
          } else {
            console.log(result)//Result output
            client.close()
          }
        })
      }
    })
  }
})
docker-compoes up

Check connection.

Tab open by terminal Move to the application directory

docker exec -it <app name>_app_cnt bash
//Enter the container
node test_db

Confirm insertion and retrieval of test data

testdb
testUser
[ { _id: 5fe60041416135000e5cd787, name: 'Taro', age: 30 } ]

Connection completed

Recommended Posts

[App development 0.5] [Node.js express Docker] Build an environment for Node.js Express MongoDB using Docker
[App development 1] [Node.js express Docker] Build an environment for Node.js Express MongoDB (mongoose) using Docker [December 2020]
[Road _node.js_1-1] Road to build Node.js Express MySQL environment using Docker
Build an Ultra96v2 development environment on Docker 1
Build a development environment for Docker + Rails6 + Postgresql
Build a development environment for Docker, java, vscode
[First team development ②] Build an environment with Docker
Build an environment of "API development + API verification using Swagger UI" with Docker
Try to build a Java development environment using Docker
[2021] Build a Docker + Vagrant environment for using React / TypeScript
I tried to build an environment using Docker (beginner)
Build a local development environment for Open Distro for Elasticsearch with multiple nodes using Docker
Build a Node.js environment with Docker
Build Java development environment (for Mac)
Build Unity development environment on docker
Use MailHog for checking emails in the development environment (using Docker)
Create an app catalog site using CLI for Microsoft 365 with Docker
Build a browser test environment using Capybara in the Docker development environment
Build a development environment for Django + MySQL + nginx with Docker Compose
Build a PureScript development environment with Docker
[Docker] Create Node.js + express + webpack environment with Docker
Build an authentication proxy server using Docker
Build a Wordpress development environment with Docker
Build an environment with Docker on AWS
Build a simple Docker + Django development environment
Build debug environment on container --Build local development environment for Rails tutorial with Docker-
How to build a Ruby on Rails environment using Docker (for Docker beginners)
How to build an environment for any version of Ruby using rbenv
Build a local development environment for Rails tutorials with Docker (Rails 6 + PostgreSQL + Webpack)
Build a WordPress development environment quickly with Docker
Build a Kotlin app using OpenJDK's Docker container
Build a simple Docker Compose + Django development environment
[Rails] How to build an environment with Docker
[Error resolution] Occurs when trying to build an environment for spring with docker
How to build an environment of [TypeScript + Vue + Express + MySQL] with Docker ~ Vue edition ~
Install Ubuntu 20.04 in virtual box on windows10 and build a development environment using docker
How to build Docker + Springboot app (for basic learning)
How to build docker environment with Gradle for intelliJ
Build an environment of Ruby2.7.x + Rails6.0.x + MySQL8.0.x with Docker
Build Docker + Laravel PHP + Vue.js development environment in 5 minutes
How to quit Docker for Mac and build a Docker development environment with Ubuntu + Vagrant
Build Java development environment with WSL2 Docker VS Code
[Docker] Build an Apache container on EC2 using dockerfile
Build an Android image for Orange Pi 4 with Docker
How to build [TypeScript + Vue + Express + MySQL] environment with Docker ~ Express ~
I tried to build the environment little by little using docker
How to build Rails, Postgres, ElasticSearch development environment with Docker
Configuration script for using docker in proxy environment on ubuntu 20.04.1
WSL2 + VSCode + Docker development environment
Build docker environment with WSL
Build Spring for Android 2.0.0 environment
multi-project docker build using jib
Build Go development environment with WSL2 + Docker Desktop + VSCode (Remote --Containers)
Procedure for building a Rails application development environment with Docker [Rails, MySQL, Docker]
Build an environment for Rails projects under Git management in Cloud9
I tried to build an http2 development environment with Eclipse + Tomcat
How to build [TypeScript + Vue + Express + MySQL] environment with Docker ~ MySQL edition ~
Build an ASP.net Core Web API environment on Docker (VSCode) Part 1
Build an ASP.NET Core Web API environment on Docker (VSCode) Part 2
How to build [TypeScript + Vue + Express + MySQL] environment with Docker ~ Sequelize ~
Build a web application development environment that uses Java, MySQL, and Redis with Docker CE for Windows