Search
Duplicate

ELK 소개, Monstache와 MongoDB연동 그리고 Docker-compose

Created time
2023/11/27 05:21
Last edited time
2023/11/28 02:28
Status
Done
tag

들어가기에 앞서

참고한 자료를 바탕으로 비전문가가 정리한 글이므로 오류가 있을 수 있습니다.
오류에 대한 지적 사항은 언제든지 환영합니다. 부디 댓글로 알려주시길 바랍니다. 감사합니다.

ELK

ELK는 Elasticsearch, Logstash, Kibana의 약자로서, 이들 세 가지 오픈 소스 도구를 조합한 데이터 시각화 및 검색 엔진 솔루션을 나타냅니다.

Elasticsearch:

분산형 검색 및 분석 엔진으로, 대량의 데이터를 신속하게 검색하고 분석할 수 있습니다. RESTful API를 사용하여 데이터 색인, 검색, 분석을 수행할 수 있습니다. 확장 가능하고 신속한 검색 및 집계 기능을 제공합니다.
Elasticsearch는 확장성이 뛰어난 오픈 소스 분석 엔진인 반면 MongoDB는 차세대 데이터베이스입니다. MongoDB와 달리 ElasticSearch는 아직 데이터의 기본 스토리지로 사용할 준비가 되어 있지 않습니다. Elasticsearch는 일반적으로 기본 엔진으로 사용됩니다.

Logstash:

다양한 소스에서 로그 및 이벤트 데이터를 수집하고 처리하는 도구입니다. 다양한 입력 플러그인을 통해 로그 데이터를 수집하고, 필터 플러그인을 사용하여 데이터를 가공하고, 다양한 출력 플러그인을 통해 여러 대상으로 전송할 수 있습니다.

Kibana:

Elasticsearch에서 수집된 데이터를 시각적으로 탐색하고 분석하는 도구입니다. 대화형 대시보드, 시각화 도구를 제공하여 데이터의 트렌드, 패턴, 관계를 이해할 수 있습니다. 사용자는 웹 기반의 인터페이스를 통해 Elasticsearch 데이터에 대한 대화식 쿼리를 실행하고 시각화를 구축할 수 있습니다. ELK 스택은 대부분의 로깅 및 모니터링 시나리오에 유용하며, 실시간 분석 및 시각화를 통해 시스템 및 애플리케이션의 상태를 파악하는 데 도움이 됩니다.

Monstache

Monstache는 MongoDB의 oplog (MongoDB 서버에서 발생하는 모든 쓰기 작업을 기록하는 특별한 컬렉션)를 사용하여 변경 사항을 실시간으로 감지하고, 이를 Elasticsearch에 색인화하여 빠르고 효율적인 검색을 지원합니다.이를 통해 MongoDB에 데이터가 추가, 수정, 삭제될 때마다 Elasticsearch가 항상 최신의 정보를 유지할 수 있습니다.
Monstache(몬스타쉬 or 몬스태쉬) 환경 설정 파일 - config.toml
# 접속하고자 하는 mongodb의 url을 입력합니다. 사전에 구성한 레플리카셋의 이름도 작성해야 합니다. mongo-url = "mongodb://mongo1:27017/servicename?replicaSet=myReplicaSet" # Elasticsearch REST API를 연결한 URL elasticsearch-urls = ["<http://elasticsearch:9200>"] # 기존 구성되어있던 mongodb에서 복사할 컬렉션 direct-read-namespaces = ["test.mycollection","test.test"] # 데이터베이스의 컬렉션 전체를 실시간 동기화하려면 데이터베이스 이름만 기입하고 특정 컬렉션만 동기화하려면 "db.collection" # 배포는 빈문자열만 입력 change-stream-namespaces = ["test.mycollection"] # 주기적으로 누적된 통계를 출력 stats = true # stats와 index-stats모두 참일 경우 Elasticsearch에 인덱싱 진행 상황에 대한 통계를 기록 index-stats = true # use the following user name for Elasticsearch basic auth #elasticsearch-user = "elastic" # use the following password for Elasticsearch basic auth #elasticsearch-password = "elasticpass" # use 4 go routines concurrently pushing documents to Elasticsearch elasticsearch-max-conns = 4 elasticsearch-max-seconds = 5 elasticsearch-max-bytes = 800000 # use the following PEM file to connections to Elasticsearch # elasticsearch-pem-file = "/path/to/elasticCert.pem" # validate connections to Elasticsearch # elastic-validate-pem-file = true # 컬렉션이 삭제되도 elasticsearch에 매핑된 인덱스는 삭제하지 않음 dropped-collections = false # 데이터베이스가 삭제되도 elasticsearch에 매핑된 인덱스는 삭제하지 않음 dropped-databases = false # do not start processing at the beginning of the MongoDB oplog # if you set the replay to true you may see version conflict messages # in the log if you had synced previously. This just means that you are replaying old docs which are already # in Elasticsearch with a newer version. Elasticsearch is preventing the old docs from overwriting new ones. replay = false # resume processing from a timestamp saved in a previous run resume = false # do not validate that progress timestamps have been saved resume-write-unsafe = true # override the name under which resume state is saved resume-name = "default" # use a custom resume strategy (tokens) instead of the default strategy (timestamps) # tokens work with MongoDB API 3.6+ while timestamps work only with MongoDB API 4.0+ resume-strategy = 1 # exclude documents whose namespace matches the following pattern namespace-exclude-regex = '^mydb\\.ignorecollection$' # turn on indexing of GridFS file content index-files = false index-as-update = true index-oplog-time = true # turn on search result highlighting of GridFS content file-highlighting = false # index GridFS files inserted into the following collections # file-namespaces = ["users.fs.files"] # print detailed information including request traces verbose = true # enable clustering mode cluster-name = 'apollo' # do not exit after full-sync, rather continue tailing the oplog exit-after-direct-reads = false
TOML
복사

MongoDB

Monstache와의 원활한 연동을 위해 MongoDB를 ReplicaSet으로 구성해야 합니다.
1.
몽고쉘 접속
$ docker exec -it mongo1 mongosh
Docker
복사
2.
하단의 레플리카 초기화 명령어 입력 (단일 레플리카 구성)
rs.initiate({ "_id": "myReplicaSet", "members": [ { "_id": 0, "host": "mongo1:27017", "priority": 2, } ] });
JavaScript
복사
3.
더미데이터 삽입
for (var i = 1; i <= 25; i++) { db.mycollection.insert( { x : i } ) }
JavaScript
복사
4.
컨테이너 재시작

Docker-compose

현재까지 소개한 도구가 벌써 5개나 되기에, 프로젝트를 실행하기 위해 로컬 환경을 어지럽히게 될 수밖에 없습니다. 또한, 각 로컬 환경마다 이 도구들을 동시에 사용하여 발생할 수 있는 각종 호환성 문제에서 자유롭지 않습니다. 이 문제를 해결하고 실 서버에 도커 컨테이너로 운영 중인 환경과 가장 흡사한 개발 환경을 구성할 수 있는 Docker-compose를 이용합니다.
Docker Compose는 여러 개의 도커 컨테이너를 정의하고 실행하기 위한 도구로, YAML 파일을 사용하여 여러 서비스, 네트워크, 볼륨 등의 설정을 표현합니다. 이를 통해 개발 및 테스트 환경을 쉽게 설정하고 여러 컨테이너 간의 상호 작용을 정의할 수 있습니다. Docker Compose 파일은 YAML 문법을 사용하며, 각 서비스의 설정, 이미지, 포트 매핑, 환경 변수, 의존 관계 등을 명시할 수 있습니다.
version: '3.9' services: mongo1: env_file: .env image: mongo:latest hostname: mongo1 container_name: mongo1 command: ["--replSet", "${MONGO_REPLSET_NAME}", "--port", "${MONGO_PORT}"] restart: always healthcheck: test: | test $$(sh /data/init-replicaSet.sh) -eq 1 interval: 10s start_period: 20s # expose: # - "27017" ports: - 27017:${MONGO_PORT} volumes: - ./mongo/init-replicaSet.sh:/data/init-replicaSet.sh - mongodbdata:/data/db # - ./mongo/key.file:/data/key.file:ro networks: - db elasticsearch: env_file: .env container_name: elasticsearch build: context: elasticsearch/ args: ELK_VERSION: $ELK_VERSION ports: - 9200:9200 - 9300:9300 volumes: - type: bind source: ./elasticsearch/config/elasticsearch.yml target: /usr/share/elasticsearch/config/elasticsearch.yml read_only: true - type: volume source: elasticsearchdata target: /usr/share/elasticsearch/data networks: - elk kibana: env_file: .env environment: - ELASTICSEARCH_HOSTS=http://elasticsearch:9200 image: kibana:8.11.1 container_name: kibana build: context: kibana/ args: ELK_VERSION: $ELK_VERSION ports: - 5601:5601 volumes: - type: bind source: ./kibana/config/kibana.yml target: /usr/share/kibana/config/kibana.yml read_only: true networks: - elk depends_on: - elasticsearch monstache: env_file: .env restart: always image: rwynn/monstache:latest container_name: monstache command: -f ./monstache.config.toml & #command: tail -F anything volumes: - ./monstache/monstache.config.toml:/monstache.config.toml - monstachedata:/monstache/ networks: - db - elk depends_on: - elasticsearch - mongo1 networks: db: driver: bridge elk: driver: bridge volumes: mongodbdata: elasticsearchdata: monstachedata:
YAML
복사
Docker Compose를 사용하면 단일 호스트에서 여러 컨테이너를 쉽게 실행하고 관리할 수 있습니다. 이는 개발, 테스트, 로컬 환경에서 애플리케이션을 쉽게 배포하고 테스트하는 데 유용합니다.

참고