Linux

반응형

MongoDB admin user 생성 하기

실습 전에 docker, docker-compose, 그리고 MongoDB 컨테이너가 구성된 yml 파일이 필요한데, 이전 블로그를 참고해도 좋습니다.
[MongoDB docker-compose로 구성 하기]

MongoDB 컨테이너가 설치되었다는 가정하에 먼저 docker ps 명령어로 컨테이너 정보를 조회 합니다.

$docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED       STATUS       PORTS                                 NAMES
dc0c851d73a7   mongo:4.4.5   "/usr/bin/mongod --b…"   2 hours ago   Up 2 hours   0.0.0.0:27017->27017/tcp              mongo1

MongoDB admin user 생성을 위해 docker 컨테이너 터미널로 접속해 보겠습니다.

$docker exec -it mongo1 bash  //container terminal 접속

root@dc0c851d73a7:/# mongo
MongoDB shell version v4.4.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("7de3fbdb-078a-476c-8003-fcd12c1dd105") }
MongoDB server version: 4.4.5
---
The server generated these startup warnings when booting:
        2022-06-30T03:40:07.230+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2022-06-30T03:40:07.727+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2022-06-30T03:40:07.727+00:00: You are running this process as the root user, which is not recommended
---
---
        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로 이동하여 순서대로 진행해 봅니다. 그 전에 replica 설정이 안되어 있을 경우 user 계정 생성이 불가할 수 있습니다.
admin db 이동 후 rs.status() 명령어로 replica set 상태를 확인해 봅니다.

> use admin       //admin db 이동
switched to db amdin

> rs.status()
{
    "ok" : 0,
    "errmsg" : "no replset config has been received",
    "code" : 94,
    "codeName" : "NotYetInitialized"
}

> db.createUser(
...   {
...      user: "admin",
...      pwd: passwordPrompt(), // or cleartext password
...      roles: [ { role: "root", db: "admin" } ]
...   }
... )  //replica 설정이 없어서 아래 오류 발생함.
Enter password:
uncaught exception: Error: couldn't add user: not master :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1386:11
@(shell):1:1

이제 다시 rs.initiate() 명령어로 default replica 정보를 설정합니다. 아래와 같이 변경된 커맨드로 전환되면 됩니다.
그리고 rs.status() 명령어로 설정을 재확인 합니다.

> rs.initiate()   //replica default 설정
r0:SECONDARY>


r0:PRIMARY> rs.status() 
{
    "set" : "r0",
    "date" : ISODate("2022-06-30T04:12:32.988Z"),
    "myState" : 1,
    "term" : NumberLong(1),
    "syncSourceHost" : "",
    "syncSourceId" : -1,
    "heartbeatIntervalMillis" : NumberLong(2000),
    "majorityVoteCount" : 1,
    "writeMajorityCount" : 1,
    "votingMembersCount" : 1,
    "writableVotingMembersCount" : 1,
    "optimes" : {
        "lastCommittedOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "lastCommittedWallTime" : ISODate("2022-06-30T04:12:25.854Z"),
        "readConcernMajorityOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "readConcernMajorityWallTime" : ISODate("2022-06-30T04:12:25.854Z"),
        "appliedOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "durableOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "lastAppliedWallTime" : ISODate("2022-06-30T04:12:25.854Z"),
        "lastDurableWallTime" : ISODate("2022-06-30T04:12:25.854Z")
    },
    "lastStableRecoveryTimestamp" : Timestamp(1656562335, 1),
    "electionCandidateMetrics" : {
        "lastElectionReason" : "electionTimeout",
        "lastElectionDate" : ISODate("2022-06-30T04:03:15.746Z"),
        "electionTerm" : NumberLong(1),
        "lastCommittedOpTimeAtElection" : {
            "ts" : Timestamp(0, 0),
            "t" : NumberLong(-1)
        },
        "lastSeenOpTimeAtElection" : {
            "ts" : Timestamp(1656561795, 1),
            "t" : NumberLong(-1)
        },
        "numVotesNeeded" : 1,
        "priorityAtElection" : 1,
        "electionTimeoutMillis" : NumberLong(10000),
        "newTermStartDate" : ISODate("2022-06-30T04:03:15.778Z"),
        "wMajorityWriteAvailabilityDate" : ISODate("2022-06-30T04:03:15.853Z")
    },
    "members" : [
        {
            "_id" : 0,
            "name" : "dc0c851d73a7:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 1945,
            "optime" : {
                "ts" : Timestamp(1656562345, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2022-06-30T04:12:25Z"),
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "",
            "electionTime" : Timestamp(1656561795, 2),
            "electionDate" : ISODate("2022-06-30T04:03:15Z"),
            "configVersion" : 1,
            "configTerm" : 1,
            "self" : true,
            "lastHeartbeatMessage" : ""
        }
    ],
    "ok" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(1656562345, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(1656562345, 1)
}

다시 db.createUser() 명령어를 실행하여 admin user 생성을 시도하면 아래 처럼 successfully 메세지와 생성된 계정 정보를 확인할 수 있습니다.
이때 password는 Prompt or cleartext 형태로 진행할 수 있습니다.

//role type: root, readWrite, dbOwner
r0:PRIMARY> db.createUser(
...   {
...      user: "admin",
...      pwd: passwordPrompt(), // or cleartext password
...      roles: [{ role: "root", db: "admin" }]
...   }
... )
Enter password:
Successfully added user: {
    "user" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
r0:PRIMARY>

이제 생성된 계정으로 MongoDB 명령어를 사용해 봅니다.

r0:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

오늘은 MongoDB에서 admin user 생성하는 방법에 대하여 정리해 봤습니다.

반응형

[Linux] 서버 용량 확인

2021. 3. 29. 17:27
반응형

linux 서버 용량 점검

용량 KB/MB/GB 표기

 ls -alh
total 40
drwxr-xr-x  10 jongpillee  staff   320B Sep 28 16:25 .
drwxr-xr-x+ 62 jongpillee  staff   1.9K Oct  6 14:28 ..
drwxr-xr-x   4 jongpillee  staff   128B Jul 26 13:54 Career
drwxr-xr-x  15 jongpillee  staff   480B Oct  6 14:24 Develop
drwxr-xr-x   3 jongpillee  staff    96B Jul 26 14:00 Doc
-rw-r--r--@  1 jongpillee  staff   4.2K Sep  1 16:07 Untitled 1.md
-rw-r--r--@  1 jongpillee  staff   2.5K Sep 28 16:25 Untitled 2.md
drwxr-xr-x   5 jongpillee  staff   160B Aug  8 09:40 Work
-rw-r--r--@  1 jongpillee  staff   2.4K Aug 19 13:58 사이판.md

folder, file 용량 조회

 du -hs \MD
300K    MD/

 du -hs \MD/*
8.0K    MD/Career
128K    MD/Develop
 12K    MD/Doc
8.0K    MD/Untitled 1.md
4.0K    MD/Untitled 2.md
132K    MD/Work
4.0K    MD/사이판.md

file disk 용량

 df -h
Filesystem       Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1s1s1  932Gi   22Gi  691Gi     4%  501138 4292962242    0%   /
devfs           190Ki  190Ki    0Bi   100%     656          0  100%   /dev
/dev/disk1s5    932Gi  8.0Gi  691Gi     2%       8 7247238840    0%   /System/Volumes/VM
/dev/disk1s3    932Gi  372Mi  691Gi     1%    2218 7247238840    0%   /System/Volumes/Preboot
/dev/disk1s6    932Gi  104Mi  691Gi     1%     469 7247238840    0%   /System/Volumes/Update
/dev/disk1s2    932Gi  209Gi  691Gi    24% 1220863 7247238840    0%   /System/Volumes/Data
map auto_home     0Bi    0Bi    0Bi   100%       0          0  100%   /System/Volumes/Data/home
/dev/disk1s1    932Gi   22Gi  691Gi     4%  502070 4292614026    0%   /System/Volumes/Update/mnt1    
반응형

'Infra > Linux' 카테고리의 다른 글

[shell] thread dump  (0) 2021.03.25
[Linux] 리눅스 명령어  (0) 2021.03.25
[Linux] war 압축  (0) 2014.01.24
[Linux] vi 명령어  (0) 2014.01.24

[shell] thread dump

2021. 3. 25. 17:25
반응형

WAS thread dump Script

```
#!/bin/bash
export pidlist=`ps -ef | grep tomcat.server | awk '{print $2}'`

date=`date + %m%d`
export LOG_DIR=/app/logs/threaddump/$date
echo "LOG_DIR = " $LOG_DIR

if [! -d $LOG_DIR ]; then
    mkdir $LOG_DIR
fi
echo "LOG_DIR making success!! "

nowtime=`date +%H:%M`
echo "nowdate=" $nowtime

ps -ef | grep tomcat.server | awk '{print $2,$9}' >> /app/logs/threaddump/$date/pidname.txt

echo "thread dump start....."

for PID in $pidlist ;do
/app/jdk/jdk1.8.0_89/bin/jstack -1 $PID >> /app/logs/threaddump/$date/${PID}_ThreadDump-1.log
echo "first thread dump ....."
done
sleep 3
echo "first thread dump success....."

for PID in $pidlist ;do
/app/jdk/jdk1.8.0_89/bin/jstack -1 $PID >> /app/logs/threaddump/$date/${PID}_ThreadDump-2.log
echo "second thread dump ....."
done
sleep 3
echo "second thread dump success....."

for PID in $pidlist ;do
/app/jdk/jdk1.8.0_89/bin/jstack -1 $PID >> /app/logs/threaddump/$date/${PID}_ThreadDump-3.log
echo "third thread dump ....."
done
sleep 3
echo "third thread dump success....."
```
반응형

'Infra > Linux' 카테고리의 다른 글

[Linux] 서버 용량 확인  (0) 2021.03.29
[Linux] 리눅스 명령어  (0) 2021.03.25
[Linux] war 압축  (0) 2014.01.24
[Linux] vi 명령어  (0) 2014.01.24

[Linux] 리눅스 명령어

2021. 3. 25. 16:32
반응형

리눅스 명령어

cp 파일 복사 하기

cp {옵션} {폴더} {복사할 폴더}
cp -r  static-root/\* /home/admin/mc\_20200106

scp 원격 간 파일 전송

scp {옵션} {폴더} {접속계정}@{목적지IP}:/{복사할 폴더}
scp  -r ./static-root/* admin@111.222.26.777:/mall_nas/static-root/  // static-root 전체 파일을 mall_nas 폴더 하위로 전송

tail (log 확인)

tail -f catalina.out //실시간 로그 확인
tail -f catalina.out | grep "ERROR" //error 만 캐치
tail -f catalina.out | grep "ERROR" | wc -l //error 카운트
tail -n 2000 catalina.out //마지막 끝에서 2000 라인까지

파일 삭제

rm -f //file
rm -r //folder ex)-rf
반응형

'Infra > Linux' 카테고리의 다른 글

[Linux] 서버 용량 확인  (0) 2021.03.29
[shell] thread dump  (0) 2021.03.25
[Linux] war 압축  (0) 2014.01.24
[Linux] vi 명령어  (0) 2014.01.24

+ Recent posts

반응형