Thank you for reading this post, don't forget to subscribe!
Вкратце:
- Replica — включает в себя Redis Master, который выполняет чтение-запись, и копирует данные на Redis Slaves, которые обслуживает запросы на чтение. При этом слейвы могут заменить мастера, если он упадёт
- Cluster — имеет смысл, если у вас данных больше, чем памяти на отдельном сервере. Кластер умеет Sharding, и клиент, запрашивающий определённый ключ, будет направлен на ту ноду, которая этот ключ хранит.
Варианты запуска Redis в Kubernetes
Что надо — это Redis с репликацией.
Как можно реализовать:
- ручной сетап —
- Redis Operator — redis-operator
- Helm чарт с кластером — https://bitnami.com/stack/redis-cluster
- Helm чарт с обычной репликацией мастер-слейв — https://bitnami.com/stack/redis
Сначала добавим пользователя gitlab - kubernetes в котором у нас будут храниться конфиги и образа.
заходим под рутом и создаём нового пользователя:
далее надо задать ему пароль
выходим из под рута
авторизуемся под нашим пользователем:
указываем новый пароль
нас выкинуло, пароль успешно задан:
создаём новый проект:
и задаём SSH ключ
генерим ключ если нету:
[root@minikub ~]# ssh-keygen
и добавляем его в гитлаб
[root@minikub ~]# cat /root/.ssh/id_rsa.pub
переходим в наш проект:
копируем URL
и выкачиваем:
[root@minikub ~]# git clone git@192.168.1.190:kubernetes/street-terminal.git
[root@minikub ~]# cd street-terminal/
Создаём namespace :
[root@minikub ~]# kubectl create namespace terminal-soft
Добавляем репозиторий и выкачиваем helm:
helm repo add bitnami https://charts.bitnami.com/bitnami
helm pull bitnami/redis
tar xvfz redis-11.0.6.tgz
выкачиваем образа:
[root@minikub redis]# docker pull bitnami/redis:6.0.8-debian-10-r0
[root@minikub redis]# docker pull bitnami/redis-exporter:1.11.1-debian-10-r12
далее перетегируем их и добавим в наш гитлаб.
[root@minikub redis]# docker tag bitnami/redis:6.0.8-debian-10-r0 192.168.1.190:4567/kubernetes/street-terminal/bitnami/redis:v1
[root@minikub redis]# docker tag bitnami/redis-exporter:1.11.1-debian-10-r12 192.168.1.190:4567/kubernetes/street-terminal/bitnami/redis-exporter:v1
чтобы можно было залить образ в gitlab registry надо добавить insecure
[root@minikub street-terminal]# cat /etc/docker/daemon.json
{ "insecure-registries":["192.168.1.190:4567"] }
[root@minikub street-terminal]# systemctl restart docker
после чего можем логиниться под нашим пользователем kubernetes:
[root@minikub street-terminal]# docker login 192.168.1.190:4567
Username: kubernetes
Password:
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
и грузим наши образа:
[root@minikub street-terminal]# docker push 192.168.1.190:4567/kubernetes/street-terminal/bitnami/redis:v1
[root@minikub street-terminal]# docker push 192.168.1.190:4567/kubernetes/street-terminal/bitnami/redis-exporter:v1
проверяем:
теперь переходим в нашу папку с redis
[root@minikub street-terminal]# cd redis/
Генерируем пароль с которым будем подключаться:
echo -n "Asergsdg2345KHJ" | base64
Получаем результат:
QXNlcmdzZGcyMzQ1S0hK
Создаём файл с паролем доступа
[root@minikub redis]# cat secret-password.yaml
[codesyntax lang="php"]
1 2 3 4 5 6 7 8 9 |
apiVersion: v1 kind: Secret metadata: name: secret-redis-terminal-soft namespace: terminal-soft type: Opaque data: redis-password: QXNlcmdzZGcyMzQ1S0hK |
[/codesyntax]
Смотрим название сторэдж класса(у нас предварительно поставлен nfs-provisoner):
[root@minikub redis]# kubectl get storageclasses.storage.k8s.io
1 2 3 |
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE <strong>managed-nfs-storage</strong> test.ru/nfs Retain Immediate false 129d standard (default) k8s.io/minikube-hostpath Delete Immediate false 183d |
Далее делаем бекап
[root@minikub redis]# cp /root/street-terminal/redis/values-production.yaml /root/street-terminal/redis/values-gitlab-production.yaml
Правим в переменных сторедж класс и дисковый объём:
[root@minikub redis]# cat /root/street-terminal/redis/values-gitlab-production.yaml | grep -iE 'storageClass|size' | grep -v '#'
storageClass: managed-nfs-storage
size: 2Gi
size: 2Gi
В этом же файле правим clusterDomain: cluster.local
[root@minikub redis]# cat values-gitlab-production.yaml | grep clusterDomain
clusterDomain: cluster.local
Если в кластере сеть используется FLANEL то отключаем networkPolicy
[root@minikub redis]# cat values-gitlab-production.yaml | grep -A3 networkPolicy
networkPolicy:
## Specifies whether a NetworkPolicy should be created
##
enabled: false
правим имена образов вот с этого:
[codesyntax lang="php"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[root@minikub redis]# cat /root/street-terminal/redis/values-gitlab-production.yaml |grep -E 'registry|repository|image|tag' | grep -v '#' image: registry: docker.io repository: bitnami/redis tag: 6.0.8-debian-10-r0 image: registry: docker.io repository: bitnami/redis-sentinel tag: 6.0.8-debian-10-r1 image: registry: docker.io repository: bitnami/redis-exporter tag: 1.11.1-debian-10-r12 image: registry: docker.io repository: bitnami/minideb tag: buster registry: docker.io repository: bitnami/minideb tag: buster |
[/codesyntax]
на это:
[codesyntax lang="php"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[root@minikub redis]# cat /root/street-terminal/redis/values-gitlab-production.yaml |grep -E 'registry|repository|image|tag' | grep -v '#' image: registry: 192.168.1.190:4567 repository: kubernetes/street-terminal/bitnami/redis tag: v1 image: registry: docker.io repository: bitnami/redis-sentinel tag: 6.0.8-debian-10-r1 image: registry: 192.168.1.190:4567 repository: kubernetes/street-terminal/bitnami/redis-exporter tag: v1 image: registry: docker.io repository: bitnami/minideb tag: buster registry: docker.io repository: bitnami/minideb tag: buster |
[/codesyntax]
Так же правим
## Use password authentication
usePassword: true
existingSecret: secret-redis-terminal-soft
usePasswordFile: true
[codesyntax lang="php"]
1 2 3 4 5 6 |
[root@minikub redis]# cat /root/street-terminal/redis/values-gitlab-production.yaml | grep -E 'existingSecret|usePassword|usePasswordFile' | grep -v '#' usePassword: true usePassword: true existingSecret: secret-redis-terminal-soft usePasswordFile: true |
[/codesyntax]
полностью файл выглядит следующим образом:
[root@minikub redis]# cat /root/street-terminal/redis/values-gitlab-production.yaml
[codesyntax lang="php"]
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 |
## Global Docker image parameters ## Please, note that this will override the image parameters, including dependencies, configured to use the global value ## Current available global Docker image parameters: imageRegistry and imagePullSecrets ## global: # imageRegistry: myRegistryName # imagePullSecrets: # - myRegistryKeySecretName # storageClass: myStorageClass redis: {} ## Bitnami Redis image version ## ref: https://hub.docker.com/r/bitnami/redis/tags/ ## image: registry: 192.168.1.190:4567 repository: kubernetes/street-terminal/bitnami/redis ## Bitnami Redis image tag ## ref: https://github.com/bitnami/bitnami-docker-redis#supported-tags-and-respective-dockerfile-links ## tag: v1 ## Specify a imagePullPolicy ## Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent' ## ref: http://kubernetes.io/docs/user-guide/images/#pre-pulling-images ## pullPolicy: IfNotPresent ## Optionally specify an array of imagePullSecrets. ## Secrets must be manually created in the namespace. ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ ## # pullSecrets: # - myRegistryKeySecretName ## String to partially override redis.fullname template (will maintain the release name) ## # nameOverride: ## String to fully override redis.fullname template ## # fullnameOverride: ## Cluster settings cluster: enabled: true slaveCount: 3 ## Use redis sentinel in the redis pod. This will disable the master and slave services and ## create one redis service with ports to the sentinel and the redis instances sentinel: enabled: false ## Require password authentication on the sentinel itself ## ref: https://redis.io/topics/sentinel usePassword: true ## Bitnami Redis Sentintel image version ## ref: https://hub.docker.com/r/bitnami/redis-sentinel/tags/ ## image: registry: docker.io repository: bitnami/redis-sentinel ## Bitnami Redis image tag ## ref: https://github.com/bitnami/bitnami-docker-redis-sentinel#supported-tags-and-respective-dockerfile-links ## tag: 6.0.8-debian-10-r1 ## Specify a imagePullPolicy ## Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent' ## ref: http://kubernetes.io/docs/user-guide/images/#pre-pulling-images ## pullPolicy: IfNotPresent ## Optionally specify an array of imagePullSecrets. ## Secrets must be manually created in the namespace. ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ ## # pullSecrets: # - myRegistryKeySecretName masterSet: mymaster initialCheckTimeout: 5 quorum: 2 downAfterMilliseconds: 60000 failoverTimeout: 18000 parallelSyncs: 1 port: 26379 ## Additional Redis configuration for the sentinel nodes ## ref: https://redis.io/topics/config ## configmap: ## Enable or disable static sentinel IDs for each replicas ## If disabled each sentinel will generate a random id at startup ## If enabled, each replicas will have a constant ID on each start-up ## staticID: false ## Configure extra options for Redis Sentinel liveness and readiness probes ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/#configure-probes) ## livenessProbe: enabled: true initialDelaySeconds: 5 periodSeconds: 5 timeoutSeconds: 5 successThreshold: 1 failureThreshold: 5 readinessProbe: enabled: true initialDelaySeconds: 5 periodSeconds: 5 timeoutSeconds: 1 successThreshold: 1 failureThreshold: 5 customLivenessProbe: {} customReadinessProbe: {} ## Redis Sentinel resource requests and limits ## ref: http://kubernetes.io/docs/user-guide/compute-resources/ # resources: # requests: # memory: 256Mi # cpu: 100m ## Redis Sentinel Service properties service: ## Redis Sentinel Service type type: ClusterIP sentinelPort: 26379 redisPort: 6379 ## Specify the nodePort value for the LoadBalancer and NodePort service types. ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport ## # sentinelNodePort: # redisNodePort: ## Provide any additional annotations which may be required. This can be used to ## set the LoadBalancer service type to internal only. ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#internal-load-balancer ## annotations: {} labels: {} loadBalancerIP: ## Specifies the Kubernetes Cluster's Domain Name. ## clusterDomain: cluster.local networkPolicy: ## Specifies whether a NetworkPolicy should be created ## enabled: false ## The Policy model to apply. When set to false, only pods with the correct ## client label will have network access to the port Redis is listening ## on. When true, Redis will accept connections from any source ## (with the correct destination port). ## # allowExternal: true ## Allow connections from other namespaces. Just set label for namespace and set label for pods (optional). ## ingressNSMatchLabels: {} ingressNSPodMatchLabels: {} serviceAccount: ## Specifies whether a ServiceAccount should be created ## create: false ## The name of the ServiceAccount to use. ## If not set and create is true, a name is generated using the fullname template name: rbac: ## Specifies whether RBAC resources should be created ## create: false role: ## Rules to create. It follows the role specification # rules: # - apiGroups: # - extensions # resources: # - podsecuritypolicies # verbs: # - use # resourceNames: # - gce.unprivileged rules: [] ## Redis pod Security Context securityContext: enabled: true fsGroup: 1001 runAsUser: 1001 ## sysctl settings for master and slave pods ## ## Uncomment the setting below to increase the net.core.somaxconn value ## # sysctls: # - name: net.core.somaxconn # value: "10000" ## Use password authentication usePassword: true ## Redis password (both master and slave) ## Defaults to a random 10-character alphanumeric string if not set and usePassword is true ## ref: https://github.com/bitnami/bitnami-docker-redis#setting-the-server-password-on-first-run ## password: ## Use existing secret (ignores previous password) existingSecret: secret-redis-terminal-soft ## Password key to be retrieved from Redis secret ## # existingSecretPasswordKey: ## Mount secrets as files instead of environment variables usePasswordFile: true ## Persist data to a persistent volume (Redis Master) persistence: ## A manually managed Persistent Volume and Claim ## Requires persistence.enabled: true ## If defined, PVC must be created manually before volume will be bound existingClaim: # Redis port redisPort: 6379 ## ## TLS configuration ## tls: # Enable TLS traffic enabled: false # # Whether to require clients to authenticate or not. authClients: true # # Name of the Secret that contains the certificates certificatesSecret: # # Certificate filename certFilename: # # Certificate Key filename certKeyFilename: # # CA Certificate filename certCAFilename: # # File containing DH params (in order to support DH based ciphers) # dhParamsFilename: ## ## Redis Master parameters ## master: ## Redis command arguments ## ## Can be used to specify command line arguments, for example: ## Note `exec` is prepended to command ## command: "/run.sh" ## Additional commands to run prior to starting Redis ## preExecCmds: "" ## Additional Redis configuration for the master nodes ## ref: https://redis.io/topics/config ## configmap: ## Redis additional command line flags ## ## Can be used to specify command line flags, for example: ## extraFlags: ## - "--maxmemory-policy volatile-ttl" ## - "--repl-backlog-size 1024mb" extraFlags: [] ## Comma-separated list of Redis commands to disable ## ## Can be used to disable Redis commands for security reasons. ## Commands will be completely disabled by renaming each to an empty string. ## ref: https://redis.io/topics/security#disabling-of-specific-commands ## disableCommands: - FLUSHDB - FLUSHALL ## Redis Master additional pod labels and annotations ## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ podLabels: {} podAnnotations: {} ## Redis Master resource requests and limits ## ref: http://kubernetes.io/docs/user-guide/compute-resources/ # resources: # requests: # memory: 256Mi # cpu: 100m ## Use an alternate scheduler, e.g. "stork". ## ref: https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/ ## # schedulerName: # Enable shared process namespace in a pod. # If set to false (default), each container will run in separate namespace, redis will have PID=1. # If set to true, the /pause will run as init process and will reap any zombie PIDs, # for example, generated by a custom exec probe running longer than a probe timeoutSeconds. # Enable this only if customLivenessProbe or customReadinessProbe is used and zombie PIDs are accumulating. # Ref: https://kubernetes.io/docs/tasks/configure-pod-container/share-process-namespace/ shareProcessNamespace: false ## Configure extra options for Redis Master liveness and readiness probes ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/#configure-probes) ## livenessProbe: enabled: true initialDelaySeconds: 5 periodSeconds: 5 timeoutSeconds: 5 successThreshold: 1 failureThreshold: 5 readinessProbe: enabled: true initialDelaySeconds: 5 periodSeconds: 5 timeoutSeconds: 1 successThreshold: 1 failureThreshold: 5 ## Configure custom probes for images other images like ## rhscl/redis-32-rhel7 rhscl/redis-5-rhel7 ## Only used if readinessProbe.enabled: false / livenessProbe.enabled: false ## # customLivenessProbe: # tcpSocket: # port: 6379 # initialDelaySeconds: 10 # periodSeconds: 5 # customReadinessProbe: # initialDelaySeconds: 30 # periodSeconds: 10 # timeoutSeconds: 5 # exec: # command: # - "container-entrypoint" # - "bash" # - "-c" # - "redis-cli set liveness-probe \"`date`\" | grep OK" customLivenessProbe: {} customReadinessProbe: {} ## Redis Master Node selectors and tolerations for pod assignment ## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector ## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#taints-and-tolerations-beta-feature ## # nodeSelector: {"beta.kubernetes.io/arch": "amd64"} # tolerations: [] ## Redis Master pod/node affinity/anti-affinity ## affinity: {} ## Redis Master Service properties service: ## Redis Master Service type type: ClusterIP port: 6379 ## Specify the nodePort value for the LoadBalancer and NodePort service types. ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport ## # nodePort: ## Provide any additional annotations which may be required. This can be used to ## set the LoadBalancer service type to internal only. ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#internal-load-balancer ## annotations: {} labels: {} loadBalancerIP: # loadBalancerSourceRanges: ["10.0.0.0/8"] ## Enable persistence using Persistent Volume Claims ## ref: http://kubernetes.io/docs/user-guide/persistent-volumes/ ## persistence: enabled: true ## The path the volume will be mounted at, useful when using different ## Redis images. path: /data ## The subdirectory of the volume to mount to, useful in dev environments ## and one PV for multiple services. subPath: "" ## redis data Persistent Volume Storage Class ## If defined, storageClassName: <storageClass> ## If set to "-", storageClassName: "", which disables dynamic provisioning ## If undefined (the default) or set to null, no storageClassName spec is ## set, choosing the default provisioner. (gp2 on AWS, standard on ## GKE, AWS & OpenStack) ## storageClass: managed-nfs-storage accessModes: - ReadWriteOnce size: 2Gi ## Persistent Volume selectors ## https://kubernetes.io/docs/concepts/storage/persistent-volumes/#selector matchLabels: {} matchExpressions: {} ## Update strategy, can be set to RollingUpdate or onDelete by default. ## https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/#updating-statefulsets statefulset: updateStrategy: RollingUpdate ## Partition update strategy ## https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#partitions # rollingUpdatePartition: ## Redis Master pod priorityClassName ## priorityClassName: {} ## An array to add extra env vars ## For example: ## extraEnvVars: ## - name: name ## value: value ## - name: other_name ## valueFrom: ## fieldRef: ## fieldPath: fieldPath ## extraEnvVars: [] ## ConfigMap with extra env vars: ## extraEnvVarsCM: [] ## Secret with extra env vars: ## extraEnvVarsSecret: [] ## ## Redis Slave properties ## Note: service.type is a mandatory parameter ## The rest of the parameters are either optional or, if undefined, will inherit those declared in Redis Master ## slave: ## Slave Service properties service: ## Redis Slave Service type type: ClusterIP ## Redis port port: 6379 ## Specify the nodePort value for the LoadBalancer and NodePort service types. ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport ## # nodePort: ## Provide any additional annotations which may be required. This can be used to ## set the LoadBalancer service type to internal only. ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#internal-load-balancer ## annotations: {} labels: {} loadBalancerIP: # loadBalancerSourceRanges: ["10.0.0.0/8"] ## Redis slave port port: 6379 ## Can be used to specify command line arguments, for example: ## Note `exec` is prepended to command ## command: "/run.sh" ## Additional commands to run prior to starting Redis ## preExecCmds: "" ## Additional Redis configuration for the slave nodes ## ref: https://redis.io/topics/config ## configmap: ## Redis extra flags extraFlags: [] ## List of Redis commands to disable disableCommands: - FLUSHDB - FLUSHALL ## Redis Slave pod/node affinity/anti-affinity ## affinity: {} ## Kubernetes Spread Constraints for pod assignment ## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-topology-spread-constraints/ ## # - maxSkew: 1 # topologyKey: node # whenUnsatisfiable: DoNotSchedule spreadConstraints: {} # Enable shared process namespace in a pod. # If set to false (default), each container will run in separate namespace, redis will have PID=1. # If set to true, the /pause will run as init process and will reap any zombie PIDs, # for example, generated by a custom exec probe running longer than a probe timeoutSeconds. # Enable this only if customLivenessProbe or customReadinessProbe is used and zombie PIDs are accumulating. # Ref: https://kubernetes.io/docs/tasks/configure-pod-container/share-process-namespace/ shareProcessNamespace: false ## Configure extra options for Redis Slave liveness and readiness probes ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/#configure-probes) ## livenessProbe: enabled: true initialDelaySeconds: 30 periodSeconds: 10 timeoutSeconds: 5 successThreshold: 1 failureThreshold: 5 readinessProbe: enabled: true initialDelaySeconds: 5 periodSeconds: 10 timeoutSeconds: 10 successThreshold: 1 failureThreshold: 5 ## Configure custom probes for images other images like ## rhscl/redis-32-rhel7 rhscl/redis-5-rhel7 ## Only used if readinessProbe.enabled: false / livenessProbe.enabled: false ## # customLivenessProbe: # tcpSocket: # port: 6379 # initialDelaySeconds: 10 # periodSeconds: 5 # customReadinessProbe: # initialDelaySeconds: 30 # periodSeconds: 10 # timeoutSeconds: 5 # exec: # command: # - "container-entrypoint" # - "bash" # - "-c" # - "redis-cli set liveness-probe \"`date`\" | grep OK" customLivenessProbe: {} customReadinessProbe: {} ## Redis slave Resource # resources: # requests: # memory: 256Mi # cpu: 100m ## Redis slave selectors and tolerations for pod assignment # nodeSelector: {"beta.kubernetes.io/arch": "amd64"} # tolerations: [] ## Use an alternate scheduler, e.g. "stork". ## ref: https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/ ## # schedulerName: ## Redis slave pod Annotation and Labels podLabels: {} podAnnotations: {} ## Redis slave pod priorityClassName # priorityClassName: {} ## Enable persistence using Persistent Volume Claims ## ref: http://kubernetes.io/docs/user-guide/persistent-volumes/ ## persistence: enabled: true ## The path the volume will be mounted at, useful when using different ## Redis images. path: /data ## The subdirectory of the volume to mount to, useful in dev environments ## and one PV for multiple services. subPath: "" ## redis data Persistent Volume Storage Class ## If defined, storageClassName: <storageClass> ## If set to "-", storageClassName: "", which disables dynamic provisioning ## If undefined (the default) or set to null, no storageClassName spec is ## set, choosing the default provisioner. (gp2 on AWS, standard on ## GKE, AWS & OpenStack) ## storageClass: managed-nfs-storage accessModes: - ReadWriteOnce size: 2Gi ## Persistent Volume selectors ## https://kubernetes.io/docs/concepts/storage/persistent-volumes/#selector matchLabels: {} matchExpressions: {} ## Update strategy, can be set to RollingUpdate or onDelete by default. ## https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/#updating-statefulsets statefulset: updateStrategy: RollingUpdate ## Partition update strategy ## https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#partitions # rollingUpdatePartition: ## An array to add extra env vars ## For example: ## extraEnvVars: ## - name: name ## value: value ## - name: other_name ## valueFrom: ## fieldRef: ## fieldPath: fieldPath ## extraEnvVars: [] ## ConfigMap with extra env vars: ## extraEnvVarsCM: [] ## Secret with extra env vars: ## extraEnvVarsSecret: [] ## Prometheus Exporter / Metrics ## metrics: enabled: true image: registry: 192.168.1.190:4567 repository: kubernetes/street-terminal/bitnami/redis-exporter tag: v1 pullPolicy: IfNotPresent ## Optionally specify an array of imagePullSecrets. ## Secrets must be manually created in the namespace. ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ ## # pullSecrets: # - myRegistryKeySecretName ## Metrics exporter resource requests and limits ## ref: http://kubernetes.io/docs/user-guide/compute-resources/ ## # resources: {} ## Extra arguments for Metrics exporter, for example: ## extraArgs: ## check-keys: myKey,myOtherKey # extraArgs: {} ## Metrics exporter pod Annotation and Labels podAnnotations: prometheus.io/scrape: "true" prometheus.io/port: "9121" # podLabels: {} # Enable this if you're using https://github.com/coreos/prometheus-operator serviceMonitor: enabled: false ## Specify a namespace if needed # namespace: monitoring # fallback to the prometheus default unless specified # interval: 10s ## Defaults to what's used if you follow CoreOS [Prometheus Install Instructions](https://github.com/bitnami/charts/tree/master/bitnami/prometheus-operator#tldr) ## [Prometheus Selector Label](https://github.com/bitnami/charts/tree/master/bitnami/prometheus-operator#prometheus-operator-1) ## [Kube Prometheus Selector Label](https://github.com/bitnami/charts/tree/master/bitnami/prometheus-operator#exporters) selector: prometheus: kube-prometheus ## Custom PrometheusRule to be defined ## The value is evaluated as a template, so, for example, the value can depend on .Release or .Chart ## ref: https://github.com/coreos/prometheus-operator#customresourcedefinitions prometheusRule: enabled: false additionalLabels: {} namespace: "" ## Redis prometheus rules ## These are just examples rules, please adapt them to your needs. ## Make sure to constraint the rules to the current redis service. # rules: # - alert: RedisDown # expr: redis_up{service="{{ template "redis.fullname" . }}-metrics"} == 0 # for: 2m # labels: # severity: error # annotations: # summary: Redis instance {{ "{{ $labels.instance }}" }} down # description: Redis instance {{ "{{ $labels.instance }}" }} is down # - alert: RedisMemoryHigh # expr: > # redis_memory_used_bytes{service="{{ template "redis.fullname" . }}-metrics"} * 100 # / # redis_memory_max_bytes{service="{{ template "redis.fullname" . }}-metrics"} # > 90 =< 100 # for: 2m # labels: # severity: error # annotations: # summary: Redis instance {{ "{{ $labels.instance }}" }} is using too much memory # description: | # Redis instance {{ "{{ $labels.instance }}" }} is using {{ "{{ $value }}" }}% of its available memory. # - alert: RedisKeyEviction # expr: | # increase(redis_evicted_keys_total{service="{{ template "redis.fullname" . }}-metrics"}[5m]) > 0 # for: 1s # labels: # severity: error # annotations: # summary: Redis instance {{ "{{ $labels.instance }}" }} has evicted keys # description: | # Redis instance {{ "{{ $labels.instance }}" }} has evicted {{ "{{ $value }}" }} keys in the last 5 minutes. rules: [] ## Metrics exporter pod priorityClassName # priorityClassName: {} service: type: ClusterIP ## Use serviceLoadBalancerIP to request a specific static IP, ## otherwise leave blank # loadBalancerIP: annotations: {} labels: {} ## ## Init containers parameters: ## volumePermissions: Change the owner of the persist volume mountpoint to RunAsUser:fsGroup ## volumePermissions: enabled: false image: registry: docker.io repository: bitnami/minideb tag: buster pullPolicy: Always ## Optionally specify an array of imagePullSecrets. ## Secrets must be manually created in the namespace. ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ ## # pullSecrets: # - myRegistryKeySecretName resources: {} # resources: # requests: # memory: 128Mi # cpu: 100m ## Redis config file ## ref: https://redis.io/topics/config ## configmap: |- # Enable AOF https://redis.io/topics/persistence#append-only-file appendonly yes # Disable RDB persistence, AOF persistence already enabled. save "" ## Sysctl InitContainer ## used to perform sysctl operation to modify Kernel settings (needed sometimes to avoid warnings) sysctlImage: enabled: false command: [] registry: docker.io repository: bitnami/minideb tag: buster pullPolicy: Always ## Optionally specify an array of imagePullSecrets. ## Secrets must be manually created in the namespace. ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ ## # pullSecrets: # - myRegistryKeySecretName mountHostSys: false resources: {} # resources: # requests: # memory: 128Mi # cpu: 100m ## PodSecurityPolicy configuration ## ref: https://kubernetes.io/docs/concepts/policy/pod-security-policy/ ## podSecurityPolicy: ## Specifies whether a PodSecurityPolicy should be created ## create: false ## Define a disruption budget ## ref: https://kubernetes.io/docs/concepts/workloads/pods/disruptions/ ## podDisruptionBudget: enabled: false minAvailable: 1 # maxUnavailable: 1 |
[/codesyntax]
Теперь можно запускать:
[root@minikub redis]# kubectl apply -f secret-password.yaml
kubectl apply -f secret-password.yaml
helm install redis-terminal-soft --namespace terminal-soft /root/git/developer-projects/street-terminal/redis/ --values /root/git/developer-projects/street-terminal/redis/values-gitlab-production.yaml
Проверяем
1 2 3 4 5 6 |
[root@minikub redis]# <strong>kubectl get service -n terminal-soft</strong> NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE redis-terminal-soft-headless ClusterIP None <none> 6379/TCP 59m redis-terminal-soft-master ClusterIP 10.111.36.163 <none> 6379/TCP 59m redis-terminal-soft-metrics ClusterIP 10.110.216.48 <none> 9121/TCP 59m redis-terminal-soft-slave ClusterIP 10.101.32.49 <none> 6379/TCP 59m |
1 2 3 4 5 6 |
[root@minikub redis]# <strong>kubectl get pod -n terminal-soft</strong> NAME READY STATUS RESTARTS AGE redis-terminal-soft-master-0 2/2 Running 0 60m redis-terminal-soft-slave-0 2/2 Running 0 60m redis-terminal-soft-slave-1 2/2 Running 0 59m redis-terminal-soft-slave-2 2/2 Running 0 59m |
1 2 3 4 5 6 |
[root@minikub redis]# <strong>kubectl get pv -n terminal-soft</strong> NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-2fdb53a6-5546-4f05-a425-7c9d3cda47bb 2Gi RWO Retain Bound terminal-soft/redis-data-redis-terminal-soft-master-0 managed-nfs-storage 121m pvc-5c1bf476-1c7e-4924-8da3-2d19225ca46e 2Gi RWO Retain Bound terminal-soft/redis-data-redis-terminal-soft-slave-2 managed-nfs-storage 60m pvc-648b7c49-2242-4497-860e-323e60425892 2Gi RWO Retain Bound terminal-soft/redis-data-redis-terminal-soft-slave-1 managed-nfs-storage 60m pvc-ec4e6051-b364-42e1-a7fe-97d7242ade5d 2Gi RWO Retain Bound terminal-soft/redis-data-redis-terminal-soft-slave-0 managed-nfs-storage 121m |
(на более старых версиях кубера можно использовать команду:
kubectl run client --image=airdock/redis-client -i --tty --rm -n terminal-soft /bin/bash)
мы же запускаем:
[root@minikub redis]# kubectl run --generator=run-pod/v1 -i --tty load-generator --image=airdock/redis-client -i --rm -n terminal-soft /bin/bash
проверяем подключение с неверным паролем:
1 2 |
root@load-generator:~# <strong>redis-cli -a Asergsdg2345K -h redis-terminal-soft-master -p 6379 ping</strong> (error) NOAUTH Authentication required. |
проверяем подключение с верным паролем:
1 2 |
root@load-generator:~# <strong>redis-cli -a Asergsdg2345KHJ -h redis-terminal-soft-master -p 6379 ping</strong> PONG |
как видим пришёл ответ PONG значит redis корректно запустился
если не удаётся удалить подвисшие PV можно использовать:
kubectl get pv | tail -n+2 | awk '{print $1}' | xargs -I{} kubectl patch pv {} -p '{"metadata":{"finalizers": null}}'
теперь можно грузить наш проект в gitlab:
[root@minikub street-terminal]# git config --global user.email "example@test.ru"
[root@minikub street-terminal]# git config --global user.name "testru"
[root@minikub street-terminal]# git add .
[root@minikub street-terminal]# git commit -m "first commit"
[root@minikub street-terminal]# git push -u origin master
как видим проект появился: