-->

[MongoDB] Docker로 MongoDB 설치

 

아 정말 오랜만에 블로그를 작성한다.

무려 8개월만인데 그동안 회사를 이직하며 문서정리를 다 회사 wiki에 하느라 개인 블로그에 투자할 시간이 없었다..

지난 1년간 이직 후 배운게 너무 많고 공부한 것도 많아서 날잡고 쓰고 싶지만 이런 저런 핑계로 미뤄왔다.. 그러나 이 것만큼은 포스팅 해야겠다고 생각이 들어서 적어본다.

 

서버는 Ubuntu 20.0 LTS 깡통 기준으로 작성하였다.

Docker 설치

$ sudo apt-get install ca-certificates curl gnupg lsb-release  
 
$ sudo mkdir -p /etc/apt/keyrings
 curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
 
$ echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
 
$ sudo apt-get update
$ sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  docker-ce-rootless-extras docker-scan-plugin pigz slirp4netns
Suggested packages:
  aufs-tools cgroupfs-mount | cgroup-lite
The following NEW packages will be installed:
  containerd.io docker-ce docker-ce-cli docker-ce-rootless-extras docker-compose-plugin docker-scan-plugin pigz slirp4netns
0 upgraded, 8 newly installed, 0 to remove and 4 not upgraded.
Need to get 74.3 kB/108 MB of archives.
After this operation, 449 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

...


# 설치 확인
$ systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since Tue 2022-08-16 09:34:33 KST; 2min 34s ago
     Docs: https://docs.docker.com
 Main PID: 11179 (dockerd)
    Tasks: 8
   Memory: 34.5M
   CGroup: /system.slice/docker.service
           └─11179 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
 
# 부팅 시 자동 실행 
$ sudo systemctl enable docker
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.

 

DockerHub로부터 mongoDB 설치

먼저 Docker Hub에 접속하여 mongoDB 이미지를 확인해준다. 

현재 7 버전대가 나오고 있는데 LTS 버전은 6.0으로 확인된다.

https://hub.docker.com/layers/library/mongo/6.0/images/sha256-e4d7cef25cd0d70c3f6f72566f5b46bda6b1978716cee6a3b341d8bd3d9fe69a?context=explore 

 

Docker

 

hub.docker.com

따라서 6.0을 설치하도록 한다.

# 소켓 권한 부여
$ sudo chmod 666 /var/run/docker.sock

# mongodb 설치
$ docker pull docker pull mongo:6.0
6.0: Pulling from dockerhub/mongo
63b3880ad1ce: Pull complete
f69d2c554348: Pull complete
2b55622443ad: Pull complete
266a1ba864ad: Pull complete
9bc7e9e472a2: Pull complete
9347ae81eebc: Pull complete
d0dc2312eb8c: Pull complete
b6bd9b1064ba: Pull complete
08ac7def05d6: Pull complete
Digest: sha256:e24fd341fac9a246328ff1ef6df1d78b480c30d0ffdf19d6e55d15358be71f36

# 설치된 이미지 확인
$ docker images
REPOSITORY               TAG       IMAGE ID       CREATED       SIZE
dockerhub/mongo          6.0       fb5fba25b25a   13 days ago   654MB

# 컨테이너 실행
$ docker run -d --name mongodb -p 27017:27017 fb5fba25b25a
fdf721e488e30391c5421259df837f84d4fbb62ea15a64f8f8c4d943bb8770c2

$ docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                   NAMES
fdf721e488e3   fb5fba25b25a   "docker-entrypoint.s…"   3 seconds ago   Up 2 seconds   0.0.0.0:27017->27017/tcp   mongodb

 

폴더 구조

data
├── app
│   └── docker-compose.yaml
└── pv
    └── mongodb
        ├── conf
        │   └── mongod.conf
        ├── data
        └── logs
            └── mongod.log

pv 폴더는 persistence volume 용도이다.

 

docker-compose.yaml 파일 작성

docker를 쓰는 사람이 docker-compose를 안쓴다는건 말이 안된다.

# docker-compose.yaml
version: '3.8'
services:
  mongodb:
    restart: always
    container_name: mongodb
    image: mongo:6.0
    ports:
      - 27017:27017
    volumes:
      - /data/pv/mongodb/data:/data/db
      - /data/pv/mongodb/logs:/var/log/mongodb
      - /data/pv/mongodb/conf/mongod.conf:/etc/mongod.conf
    command: ["mongod", "-f", "/etc/mongod.conf"]
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=1234
      - MONGO_INITDB_DATABASE=mydb

 

mongod.conf 파일 작성

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /data/db
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
#  bindIpAll: true
  bindIp: 0.0.0.0


# how the process runs
#processManagement:
#  fork: true
#  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

mongodb로 외부접속을 하기 위해서는 mongod.conf의 net 설정을 반드시 해주어야 한다. 

지금은 아무나 올 수 있게 bindIp를 0.0.0.0으로 설정함.

환경설정에 관한 추가 정보는 공식 문서에서 확인해보자.

 

컨테이너 접속

# 실행
$ docker-compose up -d
[+] Running 2/2
 ✔ Network app_default  Created                                                                                                       0.1s
 ✔ Container mongodb    Started                                                                                                       0.5s
 
 # 확인
$ docker ps
CONTAINER ID   IMAGE                      COMMAND                  CREATED         STATUS         PORTS                           NAMES
bf72535cd54b   dockerhub/mongo:6.0   "docker-entrypoint.s…"   5 minutes ago   Up 5 minutes   0.0.0.0:20717->20717/tcp, 27017/tcp   mongodb
 
 
$ docker logs mongodb
{"t":{"$date":"2023-07-27T04:05:32.295+00:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2023-07-27T04:05:32.298+00:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"main","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":17},"outgoing":{"minWireVersion":6,"maxWireVersion":17},"isInternalClient":true}}}
{"t":{"$date":"2023-07-27T04:05:32.300+00:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
{"t":{"$date":"2023-07-27T04:05:32.302+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","namespace":"config.tenantMigrationDonors"}}
{"t":{"$date":"2023-07-27T04:05:32.302+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","namespace":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2023-07-27T04:05:32.302+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"ShardSplitDonorService","namespace":"config.tenantSplitDonors"}}
{"t":{"$date":"2023-07-27T04:05:32.302+00:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
{"t":{"$date":"2023-07-27T04:05:32.303+00:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":1,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"bf72535cd54b"}}
{"t":{"$date":"2023-07-27T04:05:32.303+00:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"6.0.8","gitVersion":"3d84c0dd4e5d99be0d69003652313e7eaf4cdd74","openSSLVersion":"OpenSSL 3.0.2 15 Mar 2022","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2204","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2023-07-27T04:05:32.303+00:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Ubuntu","version":"22.04"}}}
{"t":{"$date":"2023-07-27T04:05:32.303+00:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"net":{"bindIp":"*"},"security":{"authorization":"enabled"}}}}
{"t":{"$date":"2023-07-27T04:05:32.305+00:00"},"s":"I",  "c":"STORAGE",  "id":22270,   "ctx":"initandlisten","msg":"Storage engine to use detected by data files","attr":{"dbpath":"/data/db","storageEngine":"wiredTiger"}}
{"t":{"$date":"2023-07-27T04:05:32.305+00:00"},"s":"I",  "c":"STORAGE",  "id":22297,   "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
{"t":{"$date":"2023-07-27T04:05:32.306+00:00"},"s":"I",  "c":"STORAGE",  "id":22315,   "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=1453M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],"}}
{"t":{"$date":"2023-07-27T04:05:33.303+00:00"},"s":"I",  "c":"STORAGE",  "id":4795906, "ctx":"initandlisten","msg":"WiredTiger opened","attr":{"durationMillis":997}}
{"t":{"$date":"2023-07-27T04:05:33.304+00:00"},"s":"I",  "c":"RECOVERY", "id":23987,   "ctx":"initandlisten","msg":"WiredTiger recoveryTimestamp","attr":{"recoveryTimestamp":{"$timestamp":{"t":0,"i":0}}}}
{"t":{"$date":"2023-07-27T04:05:33.319+00:00"},"s":"W",  "c":"CONTROL",  "id":5123300, "ctx":"initandlisten","msg":"vm.max_map_count is too low","attr":{"currentValue":65530,"recommendedMinimum":1677720,"maxConns":838860},"tags":["startupWarnings"]}
{"t":{"$date":"2023-07-27T04:05:33.322+00:00"},"s":"I",  "c":"NETWORK",  "id":4915702, "ctx":"initandlisten","msg":"Updated wire specification","attr":{"oldSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":17},"outgoing":{"minWireVersion":6,"maxWireVersion":17},"isInternalClient":true},"newSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":17,"maxWireVersion":17},"outgoing":{"minWireVersion":17,"maxWireVersion":17},"isInternalClient":true}}}
{"t":{"$date":"2023-07-27T04:05:33.322+00:00"},"s":"I",  "c":"REPL",     "id":5853300, "ctx":"initandlisten","msg":"current featureCompatibilityVersion value","attr":{"featureCompatibilityVersion":"6.0","context":"startup"}}
{"t":{"$date":"2023-07-27T04:05:33.323+00:00"},"s":"I",  "c":"STORAGE",  "id":5071100, "ctx":"initandlisten","msg":"Clearing temp directory"}
{"t":{"$date":"2023-07-27T04:05:33.325+00:00"},"s":"I",  "c":"CONTROL",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
{"t":{"$date":"2023-07-27T04:05:33.325+00:00"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"/data/db/diagnostic.data"}}
{"t":{"$date":"2023-07-27T04:05:33.330+00:00"},"s":"I",  "c":"REPL",     "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}}
{"t":{"$date":"2023-07-27T04:05:33.330+00:00"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
{"t":{"$date":"2023-07-27T04:05:33.333+00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"/tmp/mongodb-27017.sock"}}
{"t":{"$date":"2023-07-27T04:05:33.334+00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"0.0.0.0"}}
{"t":{"$date":"2023-07-27T04:05:33.334+00:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}


# 접속
$ docker exec -it mongodb mongosh
Current Mongosh Log ID: 64c1ef8c9f2da91f777540e2
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.1
Using MongoDB:          6.0.8
Using Mongosh:          1.10.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/
 
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.
 
test>

# admin db로 바꾸고 새 계정 생성
test> use admin
switched to db admin
admin> db.createUser({user:"minggu",pwd:"1234",roles:[{"role":"root","db":"admin"}]})
{ ok: 1 }
admin>

 

MongoDB 조작

#Ctrl + D로 MongoDB 종료, 한번 더 눌러서 컨테이너 종료
 
# 재접속
$ docker exec -it mongodb bash
root@5f64c1a55e7a:/# mongosh -u minggu -p 1234
Current Mongosh Log ID: 64c33770b43db69197467fbc
Connecting to:          mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.1
Using MongoDB:          6.0.8
Using Mongosh:          1.10.1
 
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
 
------
   The server generated these startup warnings when booting
   2023-07-28T03:32:57.729+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2023-07-28T03:32:58.747+00:00: vm.max_map_count is too low
------
 
 # 데이터베이스 확인
test> show databases
admin   132.00 KiB
config   72.00 KiB
local    96.00 KiB

# 데이터베이스 생성
test> use exhibtionDB
switched to db exhibtionDB
exhibtionDB> 
 
# 데이터 삽입 
exhibtionDB> db.exhibitions.insert({"title":"Exhibition Test","createdBy":"minggu"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("64c33da9183745bf1c891027") }
}

# 데이터베이스 목록 확인
exhibtionDB> show dbs
admin        132.00 KiB
config        60.00 KiB
exhibtionDB    8.00 KiB
local         96.00 KiB
exhibtionDB>

 

외부에서 접속도 잘 된다

+ Recent posts