[linux] MongoDB 설치하기 (tistory.com)

 

[linux] MongoDB 설치하기

저번 시간에는 aws ec2 centos linux에 MongoDB를 설치하기 위해 드라이브 공간을 추가해보는 작업을 진행하였습니다. [linux] AWS Centos EBS Volume 추가하기 (tistory.com) [linux] AWS Centos EBS Volume 추가하기 AWS Cento

nitpick92.tistory.com

서버의 문제 혹은 접속이 불가능한 상황을 대응하기 위해 주 1회 mongodb 데이터를 S3로 백업할 수 있는 방법에 대해서 정리를 해보았습니다.

 

1. s3 인입 권한을 가진 계정 생성하여 Access Token 발급

1) AWS Console IAM 접속

2) 사용자 추가
3) 직접 정책 연결
4) 정책 생성 클릭
5) JSON 인입

- 삭제 권한은 제거하고 인입 권한만 부여

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
        },
        {
            "Effect": "Deny",
            "Action": "s3:DeleteObject",
            "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
        }
    ]
}

6) 권한 정책 창에서 정책 세로고침 후 연결

7) 보안 자격 증명 창에서 엑세스 키 발급

 

2. aws cli 설치 및 연동

# AWS CLI 설치
sudo yum install awscli

# AWS CLI 구성
aws configure

3. mongodb_backup_to_s3.sh 생성

nano mongodb_backup_to_s3.sh
#!/bin/bash

# MongoDB 설정
DB_NAME="your-db"             # 백업할 MongoDB 데이터베이스 이름
COLLECTION_NAME="your-collection"  # 백업할 MongoDB 컬렉션 이름
OUTPUT_DIR="/path/to/backup/folder" # 백업 파일을 저장할 경로

# S3 설정
S3_BUCKET="your-bucket"
TODAY_DATE=$(date '+%Y-%m-%d')
S3_PATH="s3://${S3_BUCKET}/${TODAY_DATE}" # 원하는 경로

# MongoDB에서 지정된 collection 백업
mongodump --db=${DB_NAME} --collection=${COLLECTION_NAME} --out=${OUTPUT_DIR}

# 백업된 데이터를 tarball로 압축
tar -czvf ${OUTPUT_DIR}/${COLLECTION_NAME}.tar.gz -C ${OUTPUT_DIR} ${DB_NAME}

# 백업된 tarball을 S3로 업로드
aws s3 cp ${OUTPUT_DIR}/${COLLECTION_NAME}.tar.gz ${S3_PATH}/

# JSON 형식으로 백업 데이터를 변환
mongoexport --db=${DB_NAME} --collection=${COLLECTION_NAME} --out=${OUTPUT_DIR}/${COLLECTION_NAME}.json

# 백업된 JSON 데이터를 S3로 업로드
aws s3 cp ${OUTPUT_DIR}/${COLLECTION_NAME}.json ${S3_PATH}/

# (선택적) 로컬에 저장된 백업 파일 및 tarball, json 삭제
rm -rf ${OUTPUT_DIR}/${DB_NAME}
rm ${OUTPUT_DIR}/${COLLECTION_NAME}.tar.gz
rm ${OUTPUT_DIR}/${COLLECTION_NAME}.json

echo "Backup for ${COLLECTION_NAME} completed!"

4. 백업 테스트

./mongodb_backup_to_s3.sh

 

5. 자동 스케줄러(cron)

crontab -e
# 월요일 새벽 2시에 실행
0 2 * * 1 /path/to/script/mongodb_backup_to_s3.sh

 

'Server > AWS' 카테고리의 다른 글

[CentOS] Aws CloudWatch Memory 및 용량 확인  (0) 2023.04.13
[Windows] Aws CloudWatch Memory 및 용량 확인  (0) 2023.04.12
AWS Global Accelerator란?  (0) 2023.03.24

AWS CloudWatch는 애플리케이션을 모니터링할 수 있도록 해주는 서비스 입니다.

 

하지만 기본적으로 CPU 사용률, 디스크 I/O, 네트워크 부하 등 기본 지표는 제공을 하나

인스턴스 메모리 및 운영체제 디스크 사용률과 같은 운영체제의 지표는 가져오지 못합니다.

이를 위해서 CloudWatch Agent를 설치하여 메모리와 디스크 사용률을 가져올 수 있는 방법을 정리해보려고 합니다.

 

Linux(CentOS) 운영체제에서 진행해보겠습니다.

 

1. Aws IAM 역할 만들기

 

1) IAM 접속 > 역할 > 역할 생성 > AWS 서비스 > EC2 > CloudWatchAgentServerPolicy 

역할 생성
CloudWatchAgentServerPolicy 추가

2) 원하는 EC2 인스턴스에 IAM 역할을 수정해줍니다.


2. CentOS CloudWatchAgent 설치

 

1) CloudWatchAgent(amazon-cloudwatch-agent) 설치 합니다.

sudo yum install -y amazon-cloudwatch-agent

 

2) 설치된 마법사 파일을 찾아냅니다.

sudo find / -name amazon-cloudwatch-agent-config-wizard

 

3) 경로 이동 후 마법사 파일을 실행합니다.

cd /opt/aws/amazon-cloudwatch-agent/bin/
sudo ./amazon-cloudwatch-agent-config-wizard

4) Log는 모니터링하지 않고 CPU, 메모리만 나오도록 진행합니다.

$ /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
================================================================
= Welcome to the Amazon CloudWatch Agent Configuration Manager =
=                                                              =
= CloudWatch Agent allows you to collect metrics and logs from =
= your host and send them to CloudWatch. Additional CloudWatch =
= charges may apply.                                           =
================================================================
On which OS are you planning to use the agent?
1. linux
2. windows
3. darwin
default choice: [1]:
1
Trying to fetch the default region based on ec2 metadata...
Are you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:
1
Which user are you planning to run the agent?
1. root
2. cwagent
3. others
default choice: [1]:
2
Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:
2
Do you want to monitor metrics from CollectD? WARNING: CollectD must be installed or the Agent will fail to start
1. yes
2. no
default choice: [1]:
2
Do you want to monitor any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:
1
Do you want to monitor cpu metrics per core?
1. yes
2. no
default choice: [1]:
1
Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?
1. yes
2. no
default choice: [1]:
1
Do you want to aggregate ec2 dimensions (InstanceId)?
1. yes
2. no
default choice: [1]:
1
Would you like to collect your metrics at high resolution (sub-minute resolution)? This enables sub-minute resolution for all metrics, but you can customize for specific metrics in the output json file.
1. 1s
2. 10s
3. 30s
4. 60s
default choice: [4]:
4
Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
3
Current config as follows:
{
	"agent": {
		"metrics_collection_interval": 60,
		"run_as_user": "root"
	},
	"metrics": {
		"aggregation_dimensions": [
			[
				"InstanceId"
			]
		],
		"append_dimensions": {
			"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
			"ImageId": "${aws:ImageId}",
			"InstanceId": "${aws:InstanceId}",
			"InstanceType": "${aws:InstanceType}"
		},
		"metrics_collected": {
			"cpu": {
				"measurement": [
					"cpu_usage_idle",
					"cpu_usage_iowait",
					"cpu_usage_user",
					"cpu_usage_system"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				],
				"totalcpu": false
			},
			"disk": {
				"measurement": [
					"used_percent",
					"inodes_free"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				]
			},
			"diskio": {
				"measurement": [
					"io_time",
					"write_bytes",
					"read_bytes",
					"writes",
					"reads"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				]
			},
			"mem": {
				"measurement": [
					"mem_used_percent"
				],
				"metrics_collection_interval": 60
			},
			"netstat": {
				"measurement": [
					"tcp_established",
					"tcp_time_wait"
				],
				"metrics_collection_interval": 60
			},
			"swap": {
				"measurement": [
					"swap_used_percent"
				],
				"metrics_collection_interval": 60
			}
		}
	}
}
Are you satisfied with the above config? Note: it can be manually customized after the wizard completes to add additional items.
1. yes
2. no
default choice: [1]:
1
Do you have any existing CloudWatch Log Agent (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html) configuration file to import for migration?
1. yes
2. no
default choice: [2]:
2
Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
2

Saved config file to /opt/aws/amazon-cloudwatch-agent/bin/config.json successfully.
Current config as follows:
{
	"agent": {
		"metrics_collection_interval": 60,
		"run_as_user": "root"
	},
	"logs": {
		"logs_collected": {
			"files": {
				"collect_list": [
					{
						"file_path": "/var/log/nginx/access.log",
						"log_group_name": "access.log",
						"log_stream_name": "{instance_id}",
						"retention_in_days": -1
					}
				]
			}
		}
	},
	"metrics": {
		"aggregation_dimensions": [
			[
				"InstanceId"
			]
		],
		"append_dimensions": {
			"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
			"ImageId": "${aws:ImageId}",
			"InstanceId": "${aws:InstanceId}",
			"InstanceType": "${aws:InstanceType}"
		},
		"metrics_collected": {
			"cpu": {
				"measurement": [
					"cpu_usage_idle",
					"cpu_usage_iowait",
					"cpu_usage_user",
					"cpu_usage_system"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				],
				"totalcpu": false
			},
			"disk": {
				"measurement": [
					"used_percent",
					"inodes_free"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				]
			},
			"diskio": {
				"measurement": [
					"io_time",
					"write_bytes",
					"read_bytes",
					"writes",
					"reads"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				]
			},
			"mem": {
				"measurement": [
					"mem_used_percent"
				],
				"metrics_collection_interval": 60
			},
			"netstat": {
				"measurement": [
					"tcp_established",
					"tcp_time_wait"
				],
				"metrics_collection_interval": 60
			},
			"swap": {
				"measurement": [
					"swap_used_percent"
				],
				"metrics_collection_interval": 60
			}
		}
	}
}
Please check the above content of the config.
The config file is also located at /opt/aws/amazon-cloudwatch-agent/bin/config.json.
Edit it manually if needed.
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:
2
Program exits now.

 

5) 마법사로 만들어진 json 파일 호출합니다.

sudo ./amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 fil
e://opt/aws/amazon-cloudwatch-agent/bin/config.json -s

6) Agent를 실행시켜주세요.

-- agent 상태
sudo amazon-cloudwatch-agent-ctl -m ec2 -a status

-- agent 실행
sudo amazon-cloudwatch-agent-ctl -m ec2 -a start

 

7) CloudWatch > 모든 지표 정상동작 확인

정상 동작 확인

감사합니다.😊

'Server > AWS' 카테고리의 다른 글

[linux] MongoDB AWS S3 백업하기  (0) 2023.08.07
[Windows] Aws CloudWatch Memory 및 용량 확인  (0) 2023.04.12
AWS Global Accelerator란?  (0) 2023.03.24

AWS CloudWatch는 애플리케이션을 모니터링할 수 있도록 해주는 서비스 입니다.

 

하지만 기본적으로 CPU 사용률, 디스크 I/O, 네트워크 부하 등 기본 지표는 제공을 하나

인스턴스 메모리 및 운영체제 디스크 사용률과 같은 운영체제의 지표는 가져오지 못합니다.

이를 위해서 CloudWatch Agent를 설치하여 메모리와 디스크 사용률을 가져올 수 있는 방법을 정리해보려고 합니다.


Windows 운영체제에서 진행해보겠습니다.

 

1. Aws IAM 역할 만들기

 

1) IAM 접속 > 역할 > 역할 생성 > AWS 서비스 > EC2 > CloudWatchAgentServerPolicy 

역할 생성
CloudWatchAgentServerPolicy 추가

2) 원하는 EC2 인스턴스에 IAM 역할을 수정해줍니다.


2. Windows CloudWatchAgent 설치

 

1) Windows PowerShell 관리자 권한 실행을 해줍니다.


2) CloudWatchAgent 설치 파일을 다운해주세요.

Invoke-WebRequest https://s3.amazonaws.com/amazoncloudwatch-agent/windows/amd64/latest/amazon-cloudwatch-agent.msi -OutFile C:amazon-cloudwatch-agent.msi

 

3) 해당 설치 파일을 실행해주세요.

msiexec /i amazon-cloudwatch-agent.msi

 

4) Agent를 실행시켜주세요.

상태 확인
& $Env:ProgramFiles\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1 -m ec2 -a status

실행
& $Env:ProgramFiles\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1 -m ec2 -a start

 

5) 해당 위치로 접근하여 cw-config.json파일을 만들어주세요.

{
    "agent": {
        "metrics_collection_interval": 60,
        "region": "ap-northeast-2",
        "logfile": "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log",
        "debug": false
    },
    "metrics": {
        "namespace": "Windows/CloudWatchAgent",
        "metrics_collected": {

            "LogicalDisk": {
                "measurement": [
                    {
                        "name":"% Free Space",
                        "rename":"DiskFreeSpaceUtilization",
                        "unit":"Percent"
                    }

                ],
                "metrics_collection_interval": 60,
                "resources": [
                    "C:"
                ]
            },
            "Memory": {
                "measurement": [
                    {
                        "name":"% Committed Bytes In Use",
                        "unit":"Percent"
                    }
                ],
                "metrics_collection_interval": 60
            }

        },
        "append_dimensions": {
            "InstanceId": "${aws:InstanceId}"
        }
    }
}

 

6) 해당 json 파일을 실행해주세요.

& "C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1" -a fetch-config -m ec2 -s -c file:"C:\Program Files\Amazon\AmazonCloudWatchAgent\cw-config.json"

 

7) CloudWatch > 모든 지표 정상동작 확인

정상 동작 확인

감사합니다.😊

'Server > AWS' 카테고리의 다른 글

[linux] MongoDB AWS S3 백업하기  (0) 2023.08.07
[CentOS] Aws CloudWatch Memory 및 용량 확인  (0) 2023.04.13
AWS Global Accelerator란?  (0) 2023.03.24

AWS 기능중에 AWS Global Accelerator를 알아보려고 합니다.

AWS Global Accelerator는 클라이언트에 가장 가까운 정상 동작하는 엔드포인트를 찾아 연결을 도와줍니다.

 

한마디로 여러 리전에 있는 서버중 현재 사용자에 가장 가까우면서 정상 동작을 하는 서버에 연결을 도와줍니다.

가장 가까운 서버의 오류가 발견 시 자동으로 재라우팅도 도와줍니다.

 

완전 최신 기능이네요😊

😊간단 정리😊

1. elastic ip, ec2 instances, alb, nlb, public or private에서 사용이 됩니다.

2. 빠른 속도 그리고 빠른 장애 복구를 도와줍니다.

3. 항상 애플리케이션의 건강 상태를 확인합니다.

4. 애플리케이션을 글로벌 하게 만드는데 도움이 됩니다.

5. 2개의 외부 IP만 존재하여 보안적으로 안전합니다.

6. AWS Shield 덕분에 DDos에도 안전합니다.

😎장점😎

1. 가장 가까운 엔드포인트 접속을 자동으로 빠르게 라우팅을 도와줍니다.

2. 오류 발생 시 자동으로 차선의 엔드포인트로 즉각적 장애 조치를 도와줍니다.


😂단점😂

1. 사용자 인접 지역에 엣지가 없으면 오히려 느려질 수 있습니다.

2. 좀 비쌉니다...........


😉기타비교😉

1. Unicast IP vs Anycast IP

Unicast

 

Unicast  IP는 출발지와 목적지가 정확해야 하는 일대일 통신입니다.

Anycast

Anycast IP는 가장 가까운 Node와 통신하는 방식입니다.

공통적으로 전 세계의 엣지 로케이션을 사용하며 DDos보호를 위해 AWS Shield와 통합됩니다.


2. AWS Global Accelerator vs CloudFront

 

CloudFront

- 캐시 가능한 콘텐츠(이미지 및 비디오)

- 동적 콘텐츠 (API 및 동적 사이트)

 

Global Accelerator

- TCP 또는 UDP를 통한 광범위한 애플리케이션의 성능 향상

- 하나 이상의 AWS 리전에서 실행중인 애플리케이션

- 게임(UDP) Iot(MQTT) 또는 VoIP(Voice over IP)와 같은 NON-HTTP 사용.

- 고정 IP 주소가 필요한 HTTP 사용 사례

- 결정적이고 빠른 지역 장애 조치가 필요할 경우

+ Recent posts