AWS EC2, RDS 모니터링 설정 및 CloudWatch 대시보드 사용법

AWS EC2 모니터링 설정 방법

EC2 백엔드 서버 CPU 사용률, 메모리 사용률, 디스크 사용률 등 메트릭을 1분 간격으로 수집하도록 설정합니다.

EC2 서버 CPU 모니터링 간격 변경

AWS > EC2 검색 > 인스턴스 메뉴 > EC2 백엔드 서버 선택 > 모니터링 탭 > 세부 모니터링 관리 > 세부 모니터링 : 활성화 체크 > 확인 > CPU 사용률(%) 그래프 확대 > 상단 5분을 1분으로 변경 > 닫기
EC2 서버에서 기본적으로 5분 간격으로 제공되는 CPU 사용률을 1분 간격으로 제공하도록 변경합니다.
EC2 세부 모니터링 활성화 시 추가 요금이 발생할 수 있습니다.

EC2 서버에 CloudWatch Agent가 사용할 IAM 역할 연결

AWS > IAM 검색 > 액세스 관리 > 역할 메뉴 > 역할 생성 > AWS 서비스 선택 > 사용 사례 : EC2 선택 > 다음 > 권한 정책 : CloudWatchAgentServerPolicy 체크 (CloudWatch Agent가 서버 메트릭 및 로그를 CloudWatch로 전송할 수 있는 권한 부여) > 다음 > 역할 이름 : CloudWatchAgentServerRole 입력 > 역할 생성 > EC2 검색 > 인스턴스 메뉴 > 메모리 등 메트릭을 수집할 backend-server EC2 인스턴스 체크 > 작업 버튼 > 보안 > IAM 역할 수정 > IAM 역할 : 생성한 CloudWatchAgentServerRole 선택 > IAM 역할 업데이트

EC2 서버에 CloudWatch Agent 설치

AWS > EC2 검색 > name : backend-server EC2 인스턴스 ID 클릭 > 연결 > 연결 >

# Cloudwatch Agent 패키지 파일 다운로드
wget https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb

# 다운받은 Cloudwatch Agent 패키지 설치
sudo dpkg -i -E ./amazon-cloudwatch-agent.deb

Ubuntu x86-64 Cloudwatch Agent 패키지를 다운로드하고 설치합니다.

CloudWatch Agent 설정 파일 생성

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

아래와 같이 입력하며 CloudWatch Agent 설정을 완료합니다.

================================================================
= 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

# EC2 인스턴스 환경인지? 아니면 온프레미스 환경인지? 
Trying to fetch the default region based on ec2 metadata...
I! imds retry client will retry 1 timesAre you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:
1

# 리눅스에서 어떤 user로 Cloudwatch Agent를 사용할 건지? 
Which user are you planning to run the agent?
1. cwagent
2. root
3. others
default choice: [1]:
2

# 애플리케이션에서 직접 만든 커스텀 지표를 StatsD 방식으로 수집할 것인지? 
Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:
2

# CollectD를 통해 시스템 및 애플리케이션 메트릭을 수집할 건지?
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

# 컴퓨터 CPU, 메모리 등 메트릭을 모니터링 할 건지? 
Do you want to monitor any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:
1

# CloudWatch Agent에서 CPU 코어별 메트릭을 수집할 건지?
Do you want to monitor cpu metrics per core?
1. yes
2. no
default choice: [1]:
2

# 모든 메트릭에 EC2 Dimension (이미지 ID, 인스턴스 ID, 인스턴스 타입, 오토스케일링 그룹 이름) 정보를 추가해서 수집할 건지?
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

# EC2 Dimension 중에서 InstanceId를 기준으로 집계를 할 건지?
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

# 기본 메트릭 구성을 어떻게 설정할 건지? 
# Basic : 메모리 사용률(mem_used_percent), 디스크 사용률(disk_used_percent) 수집
Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
1

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": {
                        "disk": {
                                "measurement": [
                                        "used_percent"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_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

# 기존 CloudWatch Logs Agent 설정 파일을 마이그레이션할 건지?
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

# CloudWatch Agent가 X-ray(AWS의 분산 추적 시스템) 정보를 수집하게 할 건지?
Do you want the CloudWatch agent to also retrieve X-ray traces?
1. yes
2. no
default choice: [1]:
2

Existing config JSON identified and copied to:  /opt/aws/amazon-cloudwatch-agent/etc/backup-configs
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"
        },
        "metrics": {
                "aggregation_dimensions": [
                        [
                                "InstanceId"
                        ]
                ],
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "disk": {
                                "measurement": [
                                        "used_percent"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_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.

# 위 설정 정보를 AWS SSM parameter store에 저장할 건지? 
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:
2

Program exits now.

CloudWatch Agent가 메모리 사용률, 디스크 사용률을 1분마다 수집해서 CloudWatch로 보내도록 설정합니다.

CloudWatch Agent 실행

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

CloudWatch Agent 정상 실행 확인

$ sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status

status가 running 상태로 나오면 CloudWatch Agent가 정상 실행되고 있는 것입니다.

CloudWatch 수집 지표 확인

AWS > CloudWatch 검색 > 지표 > 모든 지표 메뉴 > 사용자 지정 네임스페이스 : CWAgent 클릭 > InstanceId 클릭 > EC2 백엔드 서버 InstanceId에 해당하는 메모리 사용률, 디스크 사용률 지표 확인


AWS RDS 모니터링 확인 방법

RDS CPU, 메모리 메트릭도 1분 간격으로 모니터링하면 병목 지점 파악에 도움이 됩니다.

RDS CPU, 메모리 그래프 집계 주기 변경

AWS > RDS 검색 > 데이터베이스 메뉴 > RDS DB 인스턴스 클릭 > 모니터링 > CPU 사용률(CPUUtilization) 그래프 확대 > 상단 5분을 1분으로 변경 > UTC 시간대에서 현지 시간대로 변경 > 닫기 > 사용 가능한 메모리(FreeableMemory) 그래프 확대 > 상단 5분을 1분으로 변경 > UTC 시간대에서 현지 시간대로 변경 > 닫기
RDS CloudWatch 메트릭은 기본적으로 1분 간격으로 CloudWatch에 전송되므로,
위와 같이 그래프 집계 주기만 변경하면 됩니다.


AWS ALB 모니터링 확인 방법

AWS > EC2 검색 > 로드 밸런싱 > 로드밸런서 메뉴 > 로드밸런서 이름 클릭 > 모니터링 메뉴
대상 응답 시간, 요청 수, HTTP 오류 수 등의 지표를 그래프로 볼 수 있습니다.

AWS ALB 로드밸런서는 트래픽 변화에 따라 처리 용량을 자동 확장하여 로드밸런싱 하므로,
일반적인 부하테스트에서는 대상 EC2 서버나 RDS 등의 병목 여부를 우선적으로 확인하는 것이 좋습니다.


AWS CloudWatch 사용법

CloudWatch 대시보드를 세팅하면 AWS EC2, RDS 등의 모니터링 지표를 한 눈에 체크할 수 있습니다.
부하테스트 중 CPU 또는 메모리 사용률이 급증하는 구간을 확인하면 병목 지점을 파악하는 데 도움이 됩니다.

AWS CloudWatch 대시보드 생성 방법

AWS > CloudWatch 검색 > 대시보드 메뉴 > 대시보드 생성 > 대시보드 이름 : load-test-dashboard 입력 > 대시보드 생성

EC2 모니터링 위젯 추가 방법

EC2 CPU 사용률 위젯 추가
첫 번째 위젯 추가 버튼 > 위젯 구성 : 행 (시간별 지표 비교) 선택 > 다음 > 찾아보기 탭에서 EC2 클릭 > 인스턴스별 지표 클릭 > CPUUtilization 검색 > backend-server EC2 인스턴스 CPUUtilization 지표 체크 > 그래프로 표시된 지표 탭에서 기간 : 1분 단위로 변경 > 상단 좌측 그래프 이름 : EC2 CPU 사용률 입력 > 적용 > 위젯 생성 > 저장

EC2 메모리 사용률 위젯 추가
우측 상단 + 버튼 > 위젯 구성 : 행 (시간별 지표 비교) 선택 > 다음 > 찾아보기 탭에서 CWAgent 클릭 > InstanceId 클릭 > backend-server EC2 인스턴스 mem_used_percent 지표 체크 > 그래프로 표시된 지표 탭에서 기간 : 1분 단위로 변경 > 상단 좌측 그래프 이름 : EC2 메모리 사용률 입력 > 적용 > 위젯 생성 > 저장

RDS 모니터링 위젯 추가 방법

RDS CPU 사용률 위젯 추가
우측 상단 + 버튼 > 위젯 구성 : 행 (시간별 지표 비교) 선택 > 다음 > 찾아보기 탭에서 RDS 클릭 > DBInstanceIdentifier 클릭 > CPUUtilization 검색 > test-database RDS CPUUtilization 지표 체크 > 그래프로 표시된 지표 탭에서 기간 : 1분 단위 확인 > 상단 좌측 그래프 이름 : RDS CPU 사용률 입력 > 적용 > 위젯 생성 > 저장

RDS 사용 가능한 메모리 위젯 추가
우측 상단 + 버튼 > 위젯 구성 : 행 (시간별 지표 비교) 선택 > 다음 > 찾아보기 탭에서 RDS 클릭 > DBInstanceIdentifier 클릭 > FreeableMemory 검색 > test-database RDS FreeableMemory 지표 체크 > 그래프로 표시된 지표 탭에서 기간 : 1분 단위 확인 > 상단 좌측 그래프 이름 : 사용 가능한 RDS 메모리 입력 > 적용 > 위젯 생성 > 저장

AWS CloudWatch 대시보드 확인 방법 ★

AWS > CloudWatch 검색 > 대시보드 메뉴 > load-test-dashboard 선택 > 시간 범위 : 사용자 지정 클릭 > 5분 설정
최근 5분간 각 서버의 CPU 사용률, 메모리 사용률 등을 지속적으로 모니터링합니다.
부하테스트 진행 중 쓰루풋이 정체되는 시간대에 사용률이 한계에 가장 근접한 자원을 병목 지점으로 의심해볼 수 있습니다. ★

EC2 서버 자원 실시간 확인 명령어

top

EC2 서버에 연결해서 위 명령어를 입력하면, 상단 %Cpu(s)가 현재 CPU 사용률이고 avail Mem이 사용 가능한 메모리입니다.