Jane Shao
Aplicación y del sistema registros pueden ayudar a entender el funcionamiento interno de la agrupación, registramos para los problemas de depuración y la situación cúmulo monitor también es muy útil. Y la mayoría de las aplicaciones tendrán la tala para la mayoría de las aplicaciones tradicionales se escribirá en el archivo de registro local. Para envases de aplicaciones, incluso más simple, sólo es necesario escribir la información de registro a stdout y stderr, estos registros se emitirán en un archivo en el host JSON el contenedor predeterminado, asimismo por ventana acoplable registros o troncos kubectl a la información de registro correspondiente a la vista.
Kubernetes solución más popular de recopilación de registros es Elasticsearch, Fluentd y tecnología de pila de Kibana (EFK), ahora más oficial también recomendó un esquema.
Elasticsearch es un tiempo real, distribuida y escalable motor de búsqueda que permite a texto completo y búsqueda estructurada, por lo general se utiliza para indexar y buscar una gran cantidad de datos de registro también se puede utilizar para buscar muchos tipos diferentes de documentos. Elasticsearch normalmente implementa con Kibana.
Kibana es una función del tablero de instrumentos Elasticsearch poderosa visualización de datos, Kibana le permite navegar por los datos de registro Elasticsearch a través de una interfaz web.
Fluentd es un popular colector de datos de código abierto, será montado en nodo de clúster Kubernetes Fluentd, mediante la adquisición de los archivos de registro de contenedores, el filtrado y los datos de registro de conversión, a continuación, pasa los datos a la agrupación Elasticsearch, se indexa y se almacena en el clúster .
topología
ps: mi máquina física debido a los recursos limitados, y también para implementar myweb, prometheus, Jenkins, etc., en el clúster, por lo que aquí sólo despliego EFK, condiciones normales, este programa también es suficiente para su uso.
Configuración de inicio de un clúster Elasticsearch escalable, y luego crear una aplicación Kibana en el grupo Kubernetes, la última ejecución Fluentd por DaemonSet, para que se pueda ejecutar una obra Pod Kubernetes en cada nodo.
Compruebe el estado del clúster
cúmulo cef
# ceph -s
cluster:
id: ed4d59da-c861-4da0-bbe2-8dfdea5be796
health: HEALTH_WARN
application not enabled on 1 pool(s)
services:
mon: 3 daemons, quorum bs-k8s-harbor,bs-k8s-gitlab,bs-k8s-ceph
mgr: bs-k8s-ceph(active), standbys: bs-k8s-harbor, bs-k8s-gitlab
osd: 6 osds: 6 up, 6 in
data:
pools: 1 pools, 128 pgs
objects: 92 objects, 285 MiB
usage: 6.7 GiB used, 107 GiB / 114 GiB avail
pgs: 128 active+clean
原因:这是因为未在池上启用应用程序。
解决:
# ceph osd lspools
6 webapp
# ceph osd pool application enable webapp rbd
enabled application 'rbd' on pool 'webapp'
# ceph -s
......
health: HEALTH_OK
kubernetes racimo
# kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system calico-kube-controllers-6cf5b744d7-rxt86 1/1 Running 0 47h
kube-system calico-node-25dlc 1/1 Running 2 2d4h
kube-system calico-node-49q4n 1/1 Running 2 2d4h
kube-system calico-node-4gmcp 1/1 Running 1 2d4h
kube-system calico-node-gt4bt 1/1 Running 1 2d4h
kube-system calico-node-svcdj 1/1 Running 1 2d4h
kube-system calico-node-tkrqt 1/1 Running 1 2d4h
kube-system coredns-76b74f549-dkjxd 1/1 Running 0 47h
kube-system dashboard-metrics-scraper-64c8c7d847-dqbx2 1/1 Running 0 46h
kube-system kubernetes-dashboard-85c79db674-bnvlk 1/1 Running 0 46h
kube-system metrics-server-6694c7dd66-hsbzb 1/1 Running 0 47h
kube-system traefik-ingress-controller-m8jf9 1/1 Running 0 47h
kube-system traefik-ingress-controller-r7cgl 1/1 Running 0 47h
myweb rbd-provisioner-9cf46c856-b9pm9 1/1 Running 1 7h2m
myweb wordpress-6677ff7bd-sc45d 1/1 Running 0 6h13m
myweb wordpress-mysql-6d7bd496b4-62dps 1/1 Running 0 5h51m
# kubectl top nodes
NAME CPU(cores) CPU% MEMORY(bytes) MEMORY%
20.0.0.201 563m 14% 1321Mi 103%
20.0.0.202 359m 19% 1288Mi 100%
20.0.0.203 338m 18% 1272Mi 99%
20.0.0.204 546m 14% 954Mi 13%
20.0.0.205 516m 13% 539Mi 23%
20.0.0.206 375m 9% 1123Mi 87%
Crear un espacio de nombres
Aquí voy a poner todo efk siguiente espacio de nombres de montaje. montaje: el montaje
# vim namespace.yaml
[root@bs-k8s-master01 efk]# pwd
/data/k8s/efk
[root@bs-k8s-master01 efk]# cat namespace.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: namespace.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: v1
kind: Namespace
metadata:
name: assembly
Creación dinámica de RBD Almacenamiento
La creación de la piscina ensamblaje
bs-k8s-ceph
# ceph osd pool create assembly 128
pool 'assembly' created
# ceph auth get-or-create client.assembly mon 'allow r' osd 'allow class-read, allow rwx pool=assembly' -o ceph.client.assemply.keyring
La creación de Almacenamiento
bs-k8s-master01
# ceph auth get-key client.assembly | base64
QVFBWjIzRmVDa0RnSGhBQWQ0TXJWK2YxVThGTUkrMjlva1JZYlE9PQ==
# cat ceph-efk-secret.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: ceph-jenkins-secret.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: v1
kind: Secret
metadata:
name: ceph-admin-secret
namespace: assembly
data:
key: QVFBaUptcGU0R3RDREJBQWhhM1E3NnowWG5YYUl1VVI2MmRQVFE9PQ==
type: kubernetes.io/rbd
---
apiVersion: v1
kind: Secret
metadata:
name: ceph-assembly-secret
namespace: assembly
data:
key: QVFBWjIzRmVDa0RnSGhBQWQ0TXJWK2YxVThGTUkrMjlva1JZYlE9PQ==
type: kubernetes.io/rbd
# kubectl apply -f ceph-efk-secret.yaml
secret/ceph-admin-secret created
secret/ceph-assembly-secret created
# cat ceph-efk-storageclass.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: ceph-jenkins-storageclass.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ceph-efk
namespace: assembly
annotations:
storageclass.kubernetes.io/is-default-class: "false"
provisioner: ceph.com/rbd
reclaimPolicy: Retain
parameters:
monitors: 20.0.0.205:6789,20.0.0.206:6789,20.0.0.207:6789
adminId: admin
adminSecretName: ceph-admin-secret
adminSecretNamespace: assembly
pool: assembly
fsType: xfs
userId: assembly
userSecretName: ceph-assembly-secret
imageFormat: "2"
imageFeatures: "layering"
# kubectl apply -f ceph-efk-storageclass.yaml
storageclass.storage.k8s.io/ceph-efk created
ceph rbd和kubernetes结合需要第三方插件
# cat external-storage-rbd-provisioner.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: external-storage-rbd-provisioner.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: v1
kind: ServiceAccount
metadata:
name: rbd-provisioner
namespace: assembly
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: rbd-provisioner
rules:
- apiGroups: [""]
resources: ["persistentvolumes"]
verbs: ["get", "list", "watch", "create", "delete"]
- apiGroups: [""]
resources: ["persistentvolumeclaims"]
verbs: ["get", "list", "watch", "update"]
- apiGroups: ["storage.k8s.io"]
resources: ["storageclasses"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["events"]
verbs: ["create", "update", "patch"]
- apiGroups: [""]
resources: ["endpoints"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: [""]
resources: ["services"]
resourceNames: ["kube-dns"]
verbs: ["list", "get"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: rbd-provisioner
subjects:
- kind: ServiceAccount
name: rbd-provisioner
namespace: assembly
roleRef:
kind: ClusterRole
name: rbd-provisioner
apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: rbd-provisioner
namespace: assembly
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: rbd-provisioner
namespace: assembly
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: rbd-provisioner
subjects:
- kind: ServiceAccount
name: rbd-provisioner
namespace: assembly
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: rbd-provisioner
namespace: assembly
spec:
replicas: 1
selector:
matchLabels:
app: rbd-provisioner
strategy:
type: Recreate
template:
metadata:
labels:
app: rbd-provisioner
spec:
containers:
- name: rbd-provisioner
image: "harbor.linux.com/rbd/rbd-provisioner:latest"
imagePullPolicy: IfNotPresent
env:
- name: PROVISIONER_NAME
value: ceph.com/rbd
imagePullSecrets:
- name: k8s-harbor-login
serviceAccount: rbd-provisioner
nodeSelector: ## 设置node筛选器,在特定label的节点上启动
rbd: "true"
# kubectl apply -f external-storage-rbd-provisioner.yaml
serviceaccount/rbd-provisioner created
clusterrole.rbac.authorization.k8s.io/rbd-provisioner unchanged
clusterrolebinding.rbac.authorization.k8s.io/rbd-provisioner configured
role.rbac.authorization.k8s.io/rbd-provisioner created
rolebinding.rbac.authorization.k8s.io/rbd-provisioner created
deployment.apps/rbd-provisioner created
# kubectl get pods -n assembly
NAME READY STATUS RESTARTS AGE
rbd-provisioner-9cf46c856-6qzll 1/1 Running 0 71s
La creación de Elasticsearch
创建elasticsearch-svc.yaml
定义了一个名为 elasticsearch 的 Service,指定标签app=elasticsearch,当我们将 Elasticsearch StatefulSet 与此服务关联时,服务将返回带有标签app=elasticsearch的 Elasticsearch Pods 的 DNS A 记录,然后设置clusterIP=None,将该服务设置成无头服务。最后,我们分别定义端口9200、9300,分别用于与 REST API 交互,以及用于节点间通信。
# cat elasticsearch-svc.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: elasticsearch-svc.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
kind: Service
apiVersion: v1
metadata:
name: elasticsearch
namespace: assembly
labels:
app: elasticsearch
spec:
selector:
app: elasticsearch
clusterIP: None
ports:
- port: 9200
name: rest
- port: 9300
name: inter-node
# kubectl apply -f elasticsearch-svc.yaml
service/elasticsearch created
已经为 Pod 设置了无头服务和一个稳定的域名.elasticsearch.assmbly.svc.cluster.local,接下来通过 StatefulSet 来创建具体的 Elasticsearch 的 Pod 应用.
Kubernetes StatefulSet 允许为 Pod 分配一个稳定的标识和持久化存储,Elasticsearch 需要稳定的存储来保证 Pod 在重新调度或者重启后的数据依然不变,所以需要使用 StatefulSet 来管理 Pod。
创建动态pv
# cat elasticsearch-pvc.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-18
#FileName: elasticsearch-pvc.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: ceph-elasticsearch
namespace: assembly
labels:
app: elasticsearch
spec:
storageClassName: ceph-efk
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
#kubectl apply -f ceph-efk-storageclass.yaml
# cat elasticsearch-statefulset.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: elasticsearch-storageclass.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: es-cluster
namespace: assembly
spec:
serviceName: elasticsearch
selector:
matchLabels:
app: elasticsearch
template:
metadata:
labels:
app: elasticsearch
spec:
imagePullSecrets:
- name: k8s-harbor-login
containers:
- name: elasticsearch
image: harbor.linux.com/efk/elasticsearch-oss:6.4.3
resources:
limits:
cpu: 1000m
requests:
cpu: 100m
ports:
- containerPort: 9200
name: rest
protocol: TCP
- containerPort: 9300
name: inter-node
protocol: TCP
volumeMounts:
- name: data
mountPath: /usr/share/elasticsearch/data
env:
- name: cluster.name
value: k8s-logs
- name: node.name
valueFrom:
fieldRef:
fieldPath: metadata.name
# - name: discovery.zen.ping.unicast.hosts
# value: "es-cluster-0.elasticsearch,es-cluster-1.elasticsearch,es-cluster-2.elasticsearch"
# - name: discovery.zen.minimum_master_nodes
# value: "2"
- name: ES_JAVA_OPTS
value: "-Xms512m -Xmx512m"
initContainers:
- name: fix-permissions
image: busybox
command: ["sh", "-c", "chown -R 1000:1000 /usr/share/elasticsearch/data"]
securityContext:
privileged: true
volumeMounts:
- name: data
mountPath: /usr/share/elasticsearch/data
- name: increase-vm-max-map
image: busybox
command: ["sysctl", "-w", "vm.max_map_count=262144"]
securityContext:
privileged: true
- name: increase-fd-ulimit
image: busybox
command: ["sh", "-c", "ulimit -n 65536"]
securityContext:
privileged: true
volumes:
- name: data
persistentVolumeClaim:
claimName: ceph-elasticsearch
nodeSelector: ## 设置node筛选器,在特定label的节点上启动
elasticsearch: "true"
节点打标签
# kubectl label nodes 20.0.0.204 elasticsearch=true
node/20.0.0.204 labeled
# kubectl apply -f elasticsearch-statefulset.yaml
# kubectl get pods -n assembly
NAME READY STATUS RESTARTS AGE
es-cluster-0 1/1 Running 0 2m15s
rbd-provisioner-9cf46c856-6qzll 1/1 Running 0 37m
Pods 部署完成后,我们可以通过请求一个 REST API 来检查 Elasticsearch 集群是否正常运行。使用下面的命令将本地端口9200转发到 Elasticsearch 节点(es-cluster-0)对应的端口
# kubectl port-forward es-cluster-0 9200:9200 --namespace=assembly
Forwarding from 127.0.0.1:9200 -> 9200
# curl http://localhost:9200/_cluster/state?pretty
{
"cluster_name" : "k8s-logs",
"compressed_size_in_bytes" : 234,
"cluster_uuid" : "PopKT5FLROqyBYlRvvr7kw",
"version" : 2,
"state_uuid" : "ubOKSevGRVe4iR5JXODjDA",
"master_node" : "vub5ot69Thu8igd4qeiZBg",
"blocks" : { },
"nodes" : {
"vub5ot69Thu8igd4qeiZBg" : {
"name" : "es-cluster-0",
"ephemeral_id" : "9JjNmdOyRomyYsHAO1IQ5Q",
"transport_address" : "172.20.46.85:9300",
"attributes" : { }
}
},
创建 Kibana
elasticsearch grupo comenzó con éxito, el siguiente paso puede ser para desplegar el servicio Kibana, crear un archivo con nombre de kibana.yaml.
# cat kibana.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: kibana.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: v1
kind: Service
metadata:
name: kibana
namespace: assembly
labels:
app: kibana
spec:
ports:
- port: 5601
type: NodePort
selector:
app: kibana
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: kibana
namespace: assembly
labels:
app: kibana
spec:
selector:
matchLabels:
app: kibana
template:
metadata:
labels:
app: kibana
spec:
imagePullSecrets:
- name: k8s-harbor-login
containers:
- name: kibana
image: harbor.linux.com/efk/kibana-oss:6.4.3
resources:
limits:
cpu: 1000m
requests:
cpu: 100m
env:
- name: ELASTICSEARCH_URL
value: http://elasticsearch:9200
ports:
- containerPort: 5601
nodeSelector: ## 设置node筛选器,在特定label的节点上启动
kibana: "true"
节点打标签
# kubectl label nodes 20.0.0.204 kibana=true
node/20.0.0.204 labeled
# kubectl apply -f kibana.yaml
service/kibana created
deployment.apps/kibana created
# kubectl get pods -n assembly
NAME READY STATUS RESTARTS AGE
es-cluster-0 1/1 Running 0 8m4s
kibana-598987f498-k8ff9 1/1 Running 0 70s
rbd-provisioner-9cf46c856-6qzll 1/1 Running 0 43m
定义了两个资源对象,一个 Service 和 Deployment,为了测试方便,我们将 Service 设置为了 NodePort 类型,Kibana Pod 中配置都比较简单,唯一需要注意的是我们使用 ELASTICSEARCH_URL 这个环境变量来设置Elasticsearch 集群的端点和端口,直接使用 Kubernetes DNS 即可,此端点对应服务名称为 elasticsearch,由于是一个 headless service,所以该域将解析为 Elasticsearch Pod 的 IP 地址列表
# kubectl get svc --namespace=assembly
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
elasticsearch ClusterIP None <none> 9200/TCP,9300/TCP 50m
kibana NodePort 10.68.123.234 <none> 5601:22693/TCP 2m22s
Kibana Agencia
Aquí dejo ir traefik agente Kibana
# cat kibana-ingreeroute.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: kibana-ingreeroute.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: kibana
namespace: assembly
spec:
entryPoints:
- web
routes:
- match: Host(`kibana.linux.com`)
kind: Rule
services:
- name: kibana
port: 5601
# kubectl apply -f kibana-ingreeroute.yaml
ingressroute.traefik.containo.us/kibana created
éxito agente traefik, para resolver los anfitriones locales de acogida
acceso a la web de éxito!
La creación de Fluentd
Fluentd es un polimerizador registro eficiente, que está escrito en Ruby, y puede escalar bien. Para la mayoría de las empresas, una parte relativamente pequeña Fluentd eficiente y consume recursos suficientes, otra herramienta Fluido bits más ligero, menos intensivo en recursos, pero el enchufe relativamente Fluentd no es lo suficientemente rico, por lo que, en conjunto, más Fluentd madurar, un uso más amplio, ya que se utiliza aquí herramienta de recopilación de registros Fluentd.
obras
Fluentd agarre por un conjunto dado de datos de registro de la fuente de datos, el proceso -> se convierte en un formato de datos estructurado y hacia adelante a otros servicios, tales como elasticsearch, almacenamiento de objetos y similares. soportes Fluentd más de 300 servicios de almacenamiento y de análisis de registros, por lo que en este sentido es muy flexible. Los principales pasos de la operación son los siguientes:
Fluentd primeros datos de registro de muchas fuentes
Y la bandera de datos estructurados
A continuación, la etiqueta a juego para transmitir datos a una pluralidad de servicios a un objetivo
topología Fluentd
configuración
A decir Fluentd a través de un archivo de configuración de la forma de recoger los datos de proceso,
La configuración de orígenes de registro
Aquí, por ejemplo, recoger todos los registros en el recipiente nodos Kubernetes tienen que hacer la siguiente configuración de la fuente de registro:
<source>
@id fluentd-containers.log
@type tail
path /var/log/containers/*.log
pos_file /var/log/fluentd-containers.log.pos
time_format %Y-%m-%dT%H:%M:%S.%NZ
tag raw.kubernetes.*
format json
read_from_head true
</source>
Sección anteriormente parámetros de configuración como sigue:
- id: identificador único es una referencia en el registro de origen, la identificación se puede utilizar para más de filtrado y enrutamiento de la estructura de datos de registro
- tipo: Fluentd comando integrado
tail
indica Fluentd la adquisición continua de datos a partir de una posición de la cola de la última lectura es una mayorhttp
representación de los datos recogidos por una petición GET. - ruta de acceso:
tail
el tipo específico de parámetros, la adquisición Fluentd diga/var/log/containers
todo directorio de registro, que es el directorio de las pistas contenedor de almacenamiento stdout datos de registro de salida utilizados en la ventana acoplable Kubernetes nodo. - pos_file: puesto de control, si el programa Fluentd reiniciado, utilizará la ubicación de este archivo para restaurar los datos recopilados.
- etiqueta: origen y destino para el registro o la cadena filtro personalizado emparejado, Fluentd coincide con la etiqueta de origen / destino a los datos de registro de ruta.
Configuración de enrutamiento
Lo anterior es la configuración del registro de origen, el siguiente registro para ver cómo enviar datos a Elasticsearch:
<match **>
@id elasticsearch
@type elasticsearch
@log_level info
include_tag_key true
type_name fluentd
host "#{ENV['OUTPUT_HOST']}"
port "#{ENV['OUTPUT_PORT']}"
logstash_format true
<buffer>
@type file
path /var/log/fluentd-buffers/kubernetes.system.buffer
flush_mode interval
retry_type exponential_backoff
flush_thread_count 2
flush_interval 5s
retry_forever
retry_max_interval 30
chunk_limit_size "#{ENV['OUTPUT_BUFFER_CHUNK_LIMIT']}"
queue_limit_length "#{ENV['OUTPUT_BUFFER_QUEUE_LIMIT']}"
overflow_action block
</buffer>
- coinciden: identifica una etiqueta de destino, seguido de un origen de registro de la expresión coincidente regular, aquí queremos capturar todos los registros y los envía a Elasticsearch, se debe configurar
**
. - id: un objetivo único identificador.
- escriba: export plug-in identificador de apoyo, estamos aquí para dar salida a Elasticsearch, así configurado elasticsearch, que es Fluentd un built-ins.
- log_level: Especifica el nivel de registro que desea capturar, configurado aquí para
info
indicar cualquiera de las encima de ese nivel o ese nivel (INFO, WARNING, ERROR) de registro se dirigirá a Elsasticsearch. - host / puerto: la definición de direcciones Elasticsearch, también puede configurar la información de autenticación, nuestra Elasticsearch ninguna autenticación, por lo que aquí se puede especificar directamente el host y el puerto.
- logstash_format: Elasticsearch servicio para registrar datos para construir una búsqueda índice invertido, el conjunto logstash_format
true
, formato logstash Fluentd será remitida a la estructura de los datos de registro. - Tampón: Fluentd permite el almacenamiento en caché cuando el destino no está disponible, por ejemplo, si la red se cae o el tiempo Elasticsearch disponible. configuración de memoria intermedia también ayuda a reducir disco IO
Para iniciar una sesión de recogida controlador de clúster Kubernetes directamente DasemonSet para desplegar aplicación Fluentd de manera que puede recopilar registros desde el nodo Kubernetes, garantizar que siempre se corre un recipiente Fluentd en cada nodo en el cluster.
En primer lugar, el archivo de configuración para especificar objetos Fluentd configMap, el nuevo archivo fluentd-configmap.yaml.
# cat fluentd-configmap.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: fluentd-configmap.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
kind: ConfigMap
apiVersion: v1
metadata:
name: fluentd-config
namespace: assembly
labels:
addonmanager.kubernetes.io/mode: Reconcile
data:
system.conf: |-
<system>
root_dir /tmp/fluentd-buffers/
</system>
containers.input.conf: |-
<source>
@id fluentd-containers.log
@type tail
path /var/log/containers/*.log
pos_file /var/log/es-containers.log.pos
time_format %Y-%m-%dT%H:%M:%S.%NZ
localtime
tag raw.kubernetes.*
format json
read_from_head true
</source>
# Detect exceptions in the log output and forward them as one log entry.
<match raw.kubernetes.**>
@id raw.kubernetes
@type detect_exceptions
remove_tag_prefix raw
message log
stream stream
multiline_flush_interval 5
max_bytes 500000
max_lines 1000
</match>
system.input.conf: |-
# Logs from systemd-journal for interesting services.
<source>
@id journald-docker
@type systemd
filters [{ "_SYSTEMD_UNIT": "docker.service" }]
<storage>
@type local
persistent true
</storage>
read_from_head true
tag docker
</source>
<source>
@id journald-kubelet
@type systemd
filters [{ "_SYSTEMD_UNIT": "kubelet.service" }]
<storage>
@type local
persistent true
</storage>
read_from_head true
tag kubelet
</source>
forward.input.conf: |-
# Takes the messages sent over TCP
<source>
@type forward
</source>
output.conf: |-
# Enriches records with Kubernetes metadata
<filter kubernetes.**>
@type kubernetes_metadata
</filter>
<match **>
@id elasticsearch
@type elasticsearch
@log_level info
include_tag_key true
host elasticsearch
port 9200
logstash_format true
request_timeout 30s
<buffer>
@type file
path /var/log/fluentd-buffers/kubernetes.system.buffer
flush_mode interval
retry_type exponential_backoff
flush_thread_count 2
flush_interval 5s
retry_forever
retry_max_interval 30
chunk_limit_size 2M
queue_limit_length 8
overflow_action block
</buffer>
</match>
# kubectl apply -f fluentd-configmap.yaml
configmap/fluentd-config created
El archivo de configuración anterior es un directorio y acoplables registros de contenedores estibador, kubelet recogieron registros de la aplicación, los datos recogidos se envía a Elasticsearch después del tratamiento: 9200 servicio.
A continuación, cree un archivo nuevo fluentd-daemonset.yaml
# cat fluentd-daemonset.yaml
##########################################################################
#Author: zisefeizhu
#QQ: 2********0
#Date: 2020-03-13
#FileName: fluentd-daemonset.yaml
#URL: https://www.cnblogs.com/zisefeizhu/
#Description: The test script
#Copyright (C): 2020 All rights reserved
###########################################################################
apiVersion: v1
kind: ServiceAccount
metadata:
name: fluentd-es
namespace: assembly
labels:
k8s-app: fluentd-es
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: fluentd-es
labels:
k8s-app: fluentd-es
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
rules:
- apiGroups:
- ""
resources:
- "namespaces"
- "pods"
verbs:
- "get"
- "watch"
- "list"
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: fluentd-es
labels:
k8s-app: fluentd-es
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
subjects:
- kind: ServiceAccount
name: fluentd-es
namespace: assembly
apiGroup: ""
roleRef:
kind: ClusterRole
name: fluentd-es
apiGroup: ""
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluentd-es
namespace: assembly
labels:
k8s-app: fluentd-es
version: v2.0.4
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
spec:
selector:
matchLabels:
k8s-app: fluentd-es
version: v2.0.4
template:
metadata:
labels:
k8s-app: fluentd-es
kubernetes.io/cluster-service: "true"
version: v2.0.4
# This annotation ensures that fluentd does not get evicted if the node
# supports critical pod annotation based priority scheme.
# Note that this does not guarantee admission on the nodes (#40573).
annotations:
scheduler.alpha.kubernetes.io/critical-pod: ''
spec:
serviceAccountName: fluentd-es
imagePullSecrets:
- name: k8s-harbor-login
containers:
- name: fluentd-es
image: harbor.linux.com/efk/fluentd-elasticsearch:v2.0.4
env:
- name: FLUENTD_ARGS
value: --no-supervisor -q
resources:
limits:
memory: 500Mi
requests:
cpu: 100m
memory: 200Mi
volumeMounts:
- name: varlog
mountPath: /var/log
- name: varlibdockercontainers
mountPath: /data/docker/containers
readOnly: true
- name: config-volume
mountPath: /etc/fluent/config.d
nodeSelector:
beta.kubernetes.io/fluentd-ds-ready: "true"
terminationGracePeriodSeconds: 30
volumes:
- name: varlog
hostPath:
path: /var/log
- name: varlibdockercontainers
hostPath:
path: /var/lib/docker/containers
- name: config-volume
configMap:
name: fluentd-config
nodeSelector: ## 设置node筛选器,在特定label的节点上启动
fluentd: "true"
节点打标签
# kubectl apply -f fluentd-daemonset.yaml
serviceaccount/fluentd-es created
clusterrole.rbac.authorization.k8s.io/fluentd-es created
clusterrolebinding.rbac.authorization.k8s.io/fluentd-es created
daemonset.apps/fluentd-es created
# kubectl label nodes 20.0.0.204 fluentd=true
node/20.0.0.204 labeled
# kubectl label nodes 20.0.0.205 fluentd=true
node/20.0.0.205 labeled
# kubectl label nodes 20.0.0.206 fluentd=true
node/20.0.0.206 labeled
# kubectl get pods -n assembly -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
es-cluster-0 1/1 Running 0 30m 172.20.46.85 20.0.0.204 <none> <none>
fluentd-es-5fgt7 1/1 Running 0 5m36s 172.20.46.87 20.0.0.204 <none> <none>
fluentd-es-l22nj 1/1 Running 0 5m22s 172.20.145.9 20.0.0.205 <none> <none>
fluentd-es-pnqk8 1/1 Running 0 5m18s 172.20.208.29 20.0.0.206 <none> <none>
kibana-598987f498-k8ff9 1/1 Running 0 23m 172.20.46.86 20.0.0.204 <none> <none>
rbd-provisioner-9cf46c856-6qzll 1/1 Running 0 65m 172.20.46.84 20.0.0.204 <none> <none>
Perfil delantero Fluentd que recoge los registros que utilizan el formato logstash, aquí sólo en el cuadro de texto logstash-*
puede ser adaptado a todos los datos de registro Elasticsearch vaina y, a continuación, haga clic en Siguiente, ir a la página siguiente:
Qué campo usos configuración de filtrado de los datos de registro de tiempo en esta página, en la lista desplegable, seleccione el @timestamp
campo y haga clic en Create index pattern
Crear Cuando haya terminado, haga clic en el menú de navegación de la izquierda Discover
, y luego se puede ver algunos de los histogramas y recientemente adquirida los datos de registro
Con esto se completa el despliegue de efk
piscina de inicio
# ceph osd pool application enable assembly rbd
enabled application 'rbd' on pool 'assembly'