BackEnd/MongoDB

[MongoDB] Linux 서버 독립 MongoDB 구성하기

chjs93 2021. 10. 14. 15:14

 

 

위 MongoDB 공식 홈페이지에서 community Server tar 파일을 다운 받는다.

cd mongodb
wget os별_MongoDB_downlink
tar -xvf 다운파일

 

설치 후 bin 디렉토리 하위에 다음과 같은 실행 파일들이 나온다.

  • mongo : 실행중인 MongoDB 서버에 접속하기 위한 실행파일 (독립, 복제, 샤딩 구성 구분없이 접근용)
  • mongod : MongoDB 서버를 실행시키기 위한 파일
  • mongos : MongoDB Router 를 실행시키기 위한 파일 (샤딩구성시 필요)

 

MongoDB 에는 다음 요소가 필요하다. (필요시 별도 디렉토리로 관리)

  • data : 몽고DB 의 저장소
  • log : 몽고DB log
  • config : .conf 파일

 

.conf 파일 수정

vi config/sa.conf
# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /log_경로/sa.log

# Where and how to store data.
storage:
  dbPath: /data_repository_경로
  journal:
    enabled: true
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 16

# how the process runs
processManagement:
  fork: true
  pidFilePath: /processID_경로/sa.pid
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27017
  bindIp: ::,0.0.0.0

#security:
#  authorization: enabled

bindIP를 0.0.0.0으로 설정하면 외부 접속 모두 허용됩니다. 공용 네트워크로 연결된 서버라면 인증 설정을 추가하거나 bind IP를 제한해야 하는 게 좋습니다.

 

실행

32bit, 64bit 정보가 맞지 않을시 "exec 형식 오류" 라는 에러문구가 나타난다.

[user@jiseok> ~/mongodb]$ ./bin/mongod -f ./config/sa.conf
about to fork child process, waiting until server is ready for connections.
forked process: 934491
child process started successfully, parent exiting

 

접속

[user@jiseok> ~/mongodb]$ ./mongo --port=27017
MongoDB shell version v5.0.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("24f71110-f1d0-48e2-a57a-6cdf35a3a457") }
MongoDB server version: 5.0.3
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting:
        2021-10-14T14:33:49.907+09:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2021-10-14T14:33:49.908+09:00: You are running on a NUMA machine. We suggest launching mongod like this to avoid performance problems: numactl --interleave=all mongod [other options]
        2021-10-14T14:33:49.908+09:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>

사용자 계정 생성을 위해 보안 미설정시 접근 일때 보이는 화면

 

유저생성

초기 admin 계정 생성시 몽고DB는 mongod.conf 파일의 security 부분은 주석처리 된 상태로 구동 중이어야 합니다.

# security:
#   authorization: disabled

 

admin DB 로 변경 후

> db
test
> use admin
switched to db admin

admin 계정과 특정 DB 의 사용자 계정을 만들어준다.

  • > db.createUser({
              user : "admin",
              pwd  : "---비밀번호 설정---",
              roles: [{
                    "role" : "root",
                    "db" : "admin"
              }]
    })
  • > db.createUser({
              user : "user",
              pwd : "---비밀번호 설정---",
              roles: [{
                    "role":"dbOwner",
                    "db":"데이터베이스"
              }]
    })

 

접속 테스트

  • 계정 생성이 끝났다면 sa.conf 파일의 security 부분 주석을 해제 한다.
security:
  authorization: disabled
  • MongoDB 재시작

권한 체크 mongo 입력 -> 접속권한 체크 (1이 반환되면 성공 / 0이 반환되면 실패)

> use admin
> db.auth("데이터베이스", "패스워드") # (username, password)

사용자 계정으로 접근하는 방법

mongo admin -u 데이터베이스 -p (패스워드) --port=27017

 

 

참고로 방화벽 설정은 별도로 작업해야 외부에서 접근 가능하다! (firewall-cmd 등)