Docker와 Prometheus, Grafana 연동

Jieun Yang·2024년 7월 29일

Docker

목록 보기
2/3

전체 디렉토리 구조

project-name/
├── src/
│   └── main/
│       └── java/
│       └── resources/
├── prometheus.yml
├── docker-compose.yml
├── Dockerfile
└── ...

jar 파일 안에

  • docker-compose.yml
  • prometheus.yml

가 있으면 안 됨

-> 배포되는 주체가 일체적이어야 함
-> 도커 따로, 프로메테우스 따로, 프로그램 따로

빌드 시 도커, 프로메테우스 설정 파일 제외하도록 설정

<!-- maven-resources-plugin -->

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>docker-compose.yml</exclude>
                <exclude>prometheus.yml</exclude>
            </excludes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        <!-- maven-jar-plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.1.0</version>
            <configuration>
                <excludes>
                    <exclude>docker-compose.yml</exclude>
                    <exclude>prometheus.yml</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
  • maven-resources-plugin
    • src/main/resources 디렉토리 내의 docker-compose.yml 및 prometheus.yml 파일을 빌드 시 제외
  • maven-war-plugin
    • 최종 WAR 파일 생성 시 docker-compose.yml 및 prometheus.yml 파일이 포함되지 않도록 제외

spring boot에 Prometheus 메트릭 노출을 위한 의존성 추가 pom.xml

<dependencies>
    <!-- 스프링 부트 액추에이터 의존성 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
    <!-- Micrometer Prometheus 레지스트리 의존성 -->
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
    </dependency>
</dependencies>

application.yml 추가

management:
  server:
    port: 8081 # http://localhost:8081/actuator/prometheus
  endpoints:
    web:
      exposure:
        include: "*" # 노출되는 엔드포인트 id를 나열. (exclude는 노출되지 않아야 하는..)
metrics:
  export:
    prometheus:
      enabled: true
  • 스프링부트 앱 : 8080
  • Prometheus : 9090
  • Grafana : 3000

prometheus.yml 추가

global:
  scrape_interval: 15s # Prometheus가 각 타겟에서 메트릭을 수집하는 간격
  evaluation_interval: 15s # Prometheus가 규칙을 평가하는 간격

scrape_configs:
  - job_name: 'prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['prometheus:9090']

  - job_name: 'spring-actuator'
    metrics_path: '/actuator/prometheus'
    scrape_interval: 15s
    static_configs:
      - targets: ['host.docker.internal:8081']

  - job_name: 'grafana'
    scrape_interval: 15s
    static_configs:
      - targets: ['grafana:3000']

  - job_name: 'node_exporter'
    scrape_interval: 15s
    static_configs:
      - targets: ['node_exporter:9100']

  - job_name: 'project_name'
    scrape_interval: 15s
    static_configs:
      - targets: ['project_name:27000']
  • localhost:9090:

    • Prometheus는 자기 자신을 모니터링합니다.
    • localhost는 Prometheus 컨테이너 내부에서 Prometheus 서버에 접근하는 것을 의미합니다.
  • host.docker.internal:8081:

    • Prometheus는 호스트 머신에서 실행 중인 스프링 부트 애플리케이션의 액추에이터 엔드포인트에 접근합니다.
    • host.docker.internal은 컨테이너 내부에서 호스트 머신의 네트워크 인터페이스에 접근하기 위한 주소입니다.
  • localhost:3000:

    • Prometheus는 Grafana를 모니터링합니다.
    • localhost는 Grafana 컨테이너 내부에서 Grafana 서버에 접근하는 것을 의미합니다.

docker-compose.yml 추가


services:
  prometheus:
    image: prom/prometheus
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml  # 설정 파일 도커 마운트
    ports:
      - "9090:9090"
    command:
      - '--web.enable-lifecycle' # Prometheus 서버 재시작하지 않고 설정파일 reload 
      - '--config.file=/etc/prometheus/prometheus.yml' # 설정 파일 경로 
    restart: always

  grafana:
    image: grafana/grafana
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
    depends_on:
      - prometheus
    restart: always

  node_exporter:
    image: prom/node-exporter
    container_name: node_exporter
    volumes:
      - /proc:/host/proc:ro
      - /sys:/host/sys:ro
      - /:/rootfs:ro
    command:
      - '--path.procfs=/host/proc'
      - '--path.rootfs=/rootfs'
      - '--path.sysfs=/host/sys'
      - '--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)'
    ports:
      - "9100:9100"
    restart: always
    
  project_name:
    build:
      context: /프로젝트경로
      dockerfile: Dockerfile
    ports:
      - "27000:27000"
    restart: always
  • Prometheus 서버 재시작하지 않고 변경사항 적용 (http post 요청)
    • curl -X POST http://localhost:9090/-/reload

Docker Compose 설치

1. 직접 Docker Compose 설치

# Docker Compose 설치
curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

# 실행 권한 부여
chmod +x /usr/local/bin/docker-compose

# Docker Compose 버전 확인
docker-compose --version

Docker 컨테이너는 재시작 시 상태를 유지하지 않으므로, Dockerfile을 통해 Docker Compose를 설치하는 방법을 추천


2. Dockerfile 이용하여 Docker Compose 설치

Docker Compose 설치를 Dockefile에 포함시켜, 컨테이너 빌드 시 자동으로 설치되도록 함

# Dockerfile 수정 (프로젝트 루트 디렉토리로 이동)
vim Dockerfile 

vim 이 설치 안 된 경우, yum install -y vim 로 vim 설치하거나 nano 편집기를 이용


Dockerfile

# Base image 설정
FROM centos:latest

# 필수 패키지 설치
RUN cd /etc/yum.repos.d/ && \
    sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-* && \
    sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-* && \
    yum update -y && \
    yum install -y curl && \
    curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose && \
    chmod +x /usr/local/bin/docker-compose && \
    yum clean all

# 작업 디렉터리 설정
WORKDIR /app/project

# 프로젝트 파일 복사
COPY . /app/project

# Docker Compose 버전 확인 (선택 사항)
RUN docker-compose --version

# 필요한 포트 노출 (필요에 따라 수정)
EXPOSE 27000

# Docker Compose 실행 명령
CMD ["docker-compose", "up", "-d"]



Docker Compsose 실행

docker-compose.yml 파일이 있는 디렉토리로 이동하여 Docker Compose 실행

# 프로젝트 디렉터리로 이동
cd /Users/.../IdeaProjects/project-name

# Docker Image 빌드 
docker build -t project-name
.

# Docker Compose 실행
docker-compose up -d
  • up : 정의된 서비스를 생성하고 시작
  • -d : 백그라운드에서 실행

설치 중 ....


참조

0개의 댓글