Post

06 Docker 모니터링

06 Docker 모니터링

1. Note

1. Note

    • 쉘을 해본 경험이 매우 적음.
    • 기회가 있을때 AI로 처리해서 별 의미가 없었음.
    • 기본기를 다룰 방법이 필요할듯
  • 백엔드영역
    • 백엔드가 다뤄야하는 영역이 우선적으로 어디까지 일까.
    • 전반적인 흐름을 같이 맞춰서 이어가는 것은 좋은데
    • 협력하는 사람들만의 공간과 영역은 침범하는건 위험할 듯.
  • 모니터링은 AI를 이용해서 처리해야할듯

2. Docker Logs

1. DockerLogs 기본 형태

1
2
3
4
5
6
7
8
9
10
11
12
13
# 실행한 컨테이너 name log-test

# 실행 중인 컨테이너의 모든 로그 출력
docker logs log-test

# 최근 5개의 로그 출력
docker logs --tail 5 log-test

# 실시간 로그스트림
docker logs -f log-test

# 로그에 타임스탬프 추가(도커에서 자동으로 timestamp추가함) 
docker logs --timestamps log-test

3. 로그 관리

1. Syslog 이동 처리

1
2
3
4
5
docker run \                            # 컨테이너 실행
--log-driver=syslog \                   # 이 컨테이너의 로그를 Docker 기본(json-file)이 아니라 syslog로 보냄
--log-opt syslog-address=udp://localhost:514 \  # syslog 서버 주소 (내 PC의 514 포트, UDP로 전송)
-d \                                    # 백그라운드 실행
ubuntu                                 # 사용할 이미지 (Ubuntu 파일 시스템 기반)

2. 로그 로테이션 설정

1
2
3
4
5
docker run -d \                             # 컨테이너를 백그라운드로 실행
  --name=log-rotation-test \                # 컨테이너 이름 지정
  --log-opt max-size=10m \                  # (로그 로테이션) 로그 파일 1개의 최대 크기 = 10MB
  --log-opt max-file=3 \                    # (로그 로테이션) 최대 3개 파일까지만 유지 (순환 저장)
  ubuntu                                   # Ubuntu 이미지 기반 컨테이너 생성

4. 모니터링 관리

1. 로그모니터링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash

# 첫 번째 인자로 컨테이너 이름을 받음
CONTAINER_NAME=$1
# 로그 라인 수 임계값 설정
THRESHOLD=1000

# 무한 루프로 계속 모니터링
while true; do
    # 현재 컨테이너의 로그 라인 수를 계산
    LOG_SIZE=$(docker logs $CONTAINER_NAME 2>&1 | wc -l)
    
    # 현재 시간 저장
    CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
    
    # 로그 크기가 임계값을 초과하면 경고
    if [ $LOG_SIZE -gt $THRESHOLD ]; then
        echo "[$CURRENT_TIME] Warning: Log size ($LOG_SIZE lines) exceeds threshold ($THRESHOLD) for $CONTAINER_NAME"
        
        # 선택적: 관리자에게 이메일/슬랙 등 발송
        # mail -s "Docker Log Alert" admin@example.com <<< "Container $CONTAINER_NAME log size exceeds threshold"
    else
        echo "[$CURRENT_TIME] Log size ($LOG_SIZE lines) is normal for $CONTAINER_NAME"
    fi
    
    # 1초 대기
    sleep 1
done

2. 디스크사용량

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Docker 전체 디스크 사용량 확인
docker system df

# 상세한 디스크 사용량 확인
docker system df -v

# 실시간 디스크 사용량 모니터링 스크립트 생성
cat > monitor-disk-usage.sh << 'EOF'
#!/bin/bash

while true; do
    echo "=== Docker 디스크 사용량 모니터링 === ($(date))"
    echo "1. 컨테이너 디스크 사용량:"
    docker ps --size --format "table \t\t"
    
    echo -e "\n2. 이미지 디스크 사용량:"
    docker system df -v | grep "Images space"
    
    echo -e "\n3. 볼륨 디스크 사용량:"
    docker system df -v | grep "Volumes space"
    
    echo -e "\n4. 빌드 캐시 사용량:"
    docker system df -v | grep "Build cache"
    echo "======================================="
    sleep 60
done
EOF

chmod +x monitor-disk-usage.sh

3. 디스크모니터링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
cat > advanced-disk-monitor.sh << 'EOF'
#!/bin/bash

LOG_FILE="disk_usage_log.txt"
THRESHOLD_PERCENT=80
ALERT_EMAIL="admin@example.com"

log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}

get_container_sizes() {
    docker ps -s --format ": " | while read line; do
        log_message "Container $line"
    done
}

check_disk_usage() {
    # Docker 루트 디렉토리 사용량 확인
    DOCKER_ROOT=$(docker info | grep "Docker Root Dir" | cut -d: -f2 | tr -d ' ')
    USAGE_PERCENT=$(df -h $DOCKER_ROOT | awk 'NR==2 {print $5}' | tr -d '%')
    
    log_message "Docker root directory ($DOCKER_ROOT) usage: ${USAGE_PERCENT}%"
    
    if [ $USAGE_PERCENT -gt $THRESHOLD_PERCENT ]; then
        MESSAGE="Warning: Docker disk usage is at ${USAGE_PERCENT}%"
        log_message "$MESSAGE"
        
        # 가장 큰 컨테이너 5개 리스트
        log_message "Top 5 largest containers:"
        docker ps -s --format "\t" | sort -hr | head -n 5 | \
            while read line; do
                log_message "$line"
            done
        
        # 사용하지 않는 리소스 정리 추천
        log_message "Recommended cleanup commands:"
        log_message "docker system prune -f"
        log_message "docker volume prune -f"
        log_message "docker image prune -a -f"
    fi
}

monitor_volumes() {
    log_message "Volume usage:"
    docker volume ls -q | while read vol; do
        USAGE=$(docker run --rm -v $vol:/vol alpine du -sh /vol)
        log_message "Volume $vol: $USAGE"
    done
}

# 메인 모니터링 루프
while true; do
    log_message "=== Starting disk usage check ==="
    check_disk_usage
    get_container_sizes
    monitor_volumes
    log_message "=== Completed disk usage check ==="
    echo -e "\n"
    sleep 300  # 5분 간격으로 체크
done
EOF

chmod +x advanced-disk-monitor.sh

4. 컨테이너별 상세모니터링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 컨테이너별 디스크 사용량 모니터링 스크립트
cat > container-disk-monitor.sh << 'EOF'
#!/bin/bash

echo "=== Container Disk Usage Details ==="
docker ps --format "" | while read container; do
    echo "Container: $container"
    echo "Size details:"
    docker ps -s --filter "name=$container" --format "Virtual Size: "
    echo "Top 5 largest directories:"
    docker exec $container du -h / 2>/dev/null | sort -hr | head -n 5
    echo "------------------------"
done
EOF

chmod +x container-disk-monitor.sh
./container-disk-monitor.sh
This post is licensed under CC BY 4.0 by the author.