Kubectl 플러그인
Kubectl 플러그인 (Kubectl Plugin)
CloudNativePG는 Kubernetes에서 클러스터를 관리하는 kubectl용 플러그인을 제공해요.
출처: 문서
본문
설치 (Install)
cnpg 플러그인은 다양한 방법으로 설치할 수 있어요.
:::note 에어갭(air-gapped) 시스템에서는 이전에 다운로드한 파일을 사용해 패키지 매니저로 설치하는 것이 좋은 선택일 수 있어요. :::
설치 스크립트로 (Via the installation script)
curl -sSfL \
https://github.com/cloudnative-pg/cloudnative-pg/raw/main/hack/install-cnpg-plugin.sh | \
sudo sh -s -- -b /usr/local/bin
Debian 또는 RedHat 패키지 사용 (Using the Debian or RedHat packages)
GitHub 저장소의 releases 섹션에서 관심 있는 릴리스(CloudNativePG 연산자보다 같거나 더 새로운 릴리스 선택)로 이동하면, 그 안에 Assets 섹션이 있어요. 그 섹션에는 다양한 시스템용으로 사전 빌드된 패키지가 있어요. 따라서 표준 관행과 지침에 따라 시스템에 설치할 수 있어요.
Debian 패키지 (Debian packages)
예를 들어 Intel 기반 64비트 서버용 플러그인 1.30.1 릴리스를 설치해 볼게요. 먼저 올바른 .deb 파일을 다운로드해요.
wget https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.1/kubectl-cnpg_1.30.1_linux_x86_64.deb \
--output-document kube-plugin.deb
그런 다음 슈퍼유저 권한으로 dpkg를 사용해 로컬 파일에서 설치해요:
$ sudo dpkg -i kube-plugin.deb
Selecting previously unselected package cnpg.
(Reading database ... 6688 files and directories currently installed.)
Preparing to unpack kube-plugin.deb ...
Unpacking cnpg (1.30.1) ...
Setting up cnpg (1.30.1) ...
RPM 패키지 (RPM packages)
.rpm 패키지 예시처럼, Intel 64비트 머신용 1.30.1 릴리스를 설치해 볼게요. 파일 이름을 제공하려면 --output 플래그를 사용해요.
curl -L https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.1/kubectl-cnpg_1.30.1_linux_x86_64.rpm \
--output kube-plugin.rpm
그런 다음 슈퍼유저 권한으로 yum으로 설치하면 바로 사용할 수 있어요:
$ sudo yum --disablerepo=* localinstall kube-plugin.rpm
Failed to set locale, defaulting to C.UTF-8
Dependencies resolved.
====================================================================================================
Package Architecture Version Repository Size
====================================================================================================
Installing:
cnpg x86_64 1.30.1-1 @commandline 20 M
Transaction Summary
====================================================================================================
Install 1 Package
Total size: 20 M
Installed size: 78 M
Is this ok [y/N]: y
Arch Linux 사용자 저장소(AUR) 패키지 사용 (Using the Arch Linux User Repository (AUR) Package)
AUR에서 플러그인을 설치하려면 다음 단계를 따르세요:
git clone https://aur.archlinux.org/kubectl-cnpg.git
cd kubectl-cnpg
makepkg -si
또는 선호하는 AUR-helper를 사용하세요. 예를 들어 paru:
paru -S kubectl-cnpg
Krew 사용 (Using Krew)
이미 Krew가 설치되어 있다면 다음만 실행하면 돼요:
kubectl krew install cnpg
플러그인의 새 버전이 릴리스되면 기존 설치를 다음으로 갱신할 수 있어요:
kubectl krew update
kubectl krew upgrade cnpg
Homebrew 사용 (Using Homebrew)
:::note Homebrew 커뮤니티가 Homebrew에서 kubectl-cnpg 플러그인의 가용성을 관리한다는 점을 알아두세요. :::
이미 Homebrew가 설치되어 있다면 다음만 실행하면 돼요:
brew install kubectl-cnpg
플러그인의 새 버전이 릴리스되면 기존 설치를 다음으로 갱신할 수 있어요:
brew update
brew upgrade kubectl-cnpg
:::note
kubectl 플러그인의 자동 완성은 이미 Homebrew가 관리해요. 아래 언급된 kubectl_complete-cnpg 스크립트를 만들 필요가 없어요.
:::
지원 아키텍처 (Supported Architectures)
CloudNativePG 플러그인은 현재 다음 운영체제와 아키텍처로 빌드돼요:
- Linux
- amd64
- arm 5/6/7
- arm64
- s390x
- ppc64le
- macOS
- amd64
- arm64
- Windows
- 386
- amd64
- arm 5/6/7
- arm64
자동 완성 구성 (Configuring auto-completion)
플러그인의 자동 완성을 구성하려면 헬퍼 셸 스크립트를 현재 PATH에 설치해야 해요. PATH에 /usr/local/bin이 포함돼 있다고 가정하면 다음 명령으로 수행할 수 있어요:
cat > kubectl_complete-cnpg <<EOF
#!/usr/bin/env sh
# Call the __complete command passing it all arguments
kubectl cnpg __complete "\$@"
EOF
chmod +x kubectl_complete-cnpg
# Important: the following command may require superuser permission
sudo mv kubectl_complete-cnpg /usr/local/bin
:::info[Important] 스크립트의 이름은 kubectl 자동 완성 프로세스가 사용하므로 정확히 제공된 이름이어야 해요. :::
사용 (Use)
플러그인이 설치·배포되면 다음과 같이 사용을 시작할 수 있어요:
kubectl cnpg COMMAND [ARGS...]
:::note
플러그인은 표준 출력 채널이 터미널에 연결되었는지 자동으로 감지해요. 그 경우 명령 출력에 ANSI 색상을 추가할 수 있어요. 색상을 비활성화하려면 명령과 함께 --color=never 옵션을 사용하세요.
:::
설치 매니페스트 생성 (Generation of installation manifests)
cnpg 플러그인은 연산자 설치용 YAML 매니페스트를 생성하는 데 사용할 수 있어요. 이 옵션은 레플리카 수, 설치 네임스페이스, watch 네임스페이스 등 일부 기본 구성을 오버라이드하려 할 때 일반적으로 사용돼요.
세부 사항과 사용 가능한 옵션은 다음을 실행하세요:
kubectl cnpg install generate --help
주요 옵션:
-n: 연산자를 설치할 네임스페이스 지정 (기본값:cnpg-system)--control-plane: true로 설정하면 연산자 배포에node-role.kubernetes.io/control-plane에 대한 톨러레이션과 어피니티가 포함돼요.--replicas: 배포의 레플리카 수 설정--watch-namespace: watch할 네임스페이스의 콤마 구분 목록 지정 (기본값: 모든 네임스페이스)--version: 설치할 연산자의 마이너 버전 정의, 예:1.23. 마이너 버전이 지정되면 플러그인은 그 마이너 버전의 최신 패치 버전을 설치해요. 버전이 제공되지 않으면 플러그인은 연산자의 최신MAJOR.MINOR.PATCH버전을 설치해요.
연산자를 설치할 YAML 매니페스트를 생성하는 generate 명령의 예:
kubectl cnpg install generate \
-n king \
--version 1.23 \
--replicas 3 \
--watch-namespace "albert, bb, freddie" \
> operator.yaml
위 명령의 플래그 의미:
-n king: CNPG 연산자를king네임스페이스에 설치--version 1.23: 마이너 버전 1.23의 최신 패치 버전 설치--replicas 3: 연산자를 3개의 레플리카로 설치--watch-namespace "albert, bb, freddie": 연산자가albert,bb,freddie네임스페이스의 변경만 watch하도록 함
상태 (Status)
status 명령은 클러스터의 현재 상태에 대한 개요를 제공하며, 다음을 포함해요:
- 일반 정보: 클러스터 이름, PostgreSQL의 시스템 ID, 인스턴스 수, 현재 타임라인과 WAL 내 위치
- 백업: 복구 가능 지점, 그리고 프라이머리(또는 레플리카 클러스터의 경우 지정된 프라이머리)의
pg_stat_archiver뷰가 반환하는 WAL 아카이빙 상태 - 스트리밍 복제: 프라이머리 인스턴스의
pg_stat_replication뷰에서 직접 가져온 정보 - 인스턴스: 각 Postgres 인스턴스에 대한 정보로, 각 인스턴스 매니저가 직접 제공. 스탠바이의 경우
Current LSN필드는 복구 중에 재생된 최신 write-ahead 로그 위치(replay LSN)에 해당해요.
:::info[Important]
위 상태 정보는 서로 다른 시간과 위치에서 가져오므로, 반환되는 값이 약간 불일치할 수 있어요. 예를 들어 메인 헤더의 Current Write LSN 위치는 두 개의 서로 다른 시간 간격에 찍히기 때문에 인스턴스 상태의 Current LSN 필드와 다를 수 있어요.
:::
kubectl cnpg status sandbox
Cluster Summary
Name: default/sandbox
System ID: 7423474350493388827
PostgreSQL Image: ghcr.io/cloudnative-pg/postgresql:16.4
Primary instance: sandbox-1
Primary start time: 2024-10-08 18:31:57 +0000 UTC (uptime 1m14s)
Status: Cluster in healthy state
Instances: 3
Ready instances: 3
Size: 126M
Current Write LSN: 0/604DE38 (Timeline: 1 - WAL File: 000000010000000000000006)
Continuous Backup status
Not configured
Streaming Replication status
Replication Slots Enabled
Name Sent LSN Write LSN Flush LSN Replay LSN Write Lag Flush Lag Replay Lag State Sync State Sync Priority Replication Slot
---- -------- --------- --------- ---------- --------- --------- ---------- ----- ---------- ------------- ----------------
sandbox-2 0/604DE38 0/604DE38 0/604DE38 0/604DE38 00:00:00 00:00:00 00:00:00 streaming async 0 active
sandbox-3 0/604DE38 0/604DE38 0/604DE38 0/604DE38 00:00:00 00:00:00 00:00:00 streaming async 0 active
Instances status
Name Current LSN Replication role Status QoS Manager Version Node
---- ----------- ---------------- ------ --- --------------- ----
sandbox-1 0/604DE38 Primary OK BestEffort 1.30.1 k8s-eu-worker
sandbox-2 0/604DE38 Standby (async) OK BestEffort 1.30.1 k8s-eu-worker2
sandbox-3 0/604DE38 Standby (async) OK BestEffort 1.30.1 k8s-eu-worker
더 상세한 상태 정보가 필요하면 --verbose 옵션(줄여서 -v)을 사용하세요. 플래그를 반복할 때마다 상세 수준이 증가해요:
kubectl cnpg status sandbox --verbose
Cluster Summary
Name: default/sandbox
System ID: 7423474350493388827
PostgreSQL Image: ghcr.io/cloudnative-pg/postgresql:16.4
Primary instance: sandbox-1
Primary start time: 2024-10-08 18:31:57 +0000 UTC (uptime 2m4s)
Status: Cluster in healthy state
Instances: 3
Ready instances: 3
Size: 126M
Current Write LSN: 0/6053720 (Timeline: 1 - WAL File: 000000010000000000000006)
Continuous Backup status
Not configured
Physical backups
No running physical backups found
Streaming Replication status
Replication Slots Enabled
Name Sent LSN Write LSN Flush LSN Replay LSN Write Lag Flush Lag Replay Lag State Sync State Sync Priority Replication Slot Slot Restart LSN Slot WAL Status Slot Safe WAL Size
---- -------- --------- --------- ---------- --------- --------- ---------- ----- ---------- ------------- ---------------- ---------------- --------------- ------------------
sandbox-2 0/6053720 0/6053720 0/6053720 0/6053720 00:00:00 00:00:00 00:00:00 streaming async 0 active 0/6053720 reserved NULL
sandbox-3 0/6053720 0/6053720 0/6053720 0/6053720 00:00:00 00:00:00 00:00:00 streaming async 0 active 0/6053720 reserved NULL
Unmanaged Replication Slot Status
No unmanaged replication slots found
Managed roles status
No roles managed
Tablespaces status
No managed tablespaces
Pod Disruption Budgets status
Name Role Expected Pods Current Healthy Minimum Desired Healthy Disruptions Allowed
---- ---- ------------- --------------- ----------------------- -------------------
sandbox replica 2 2 1 1
sandbox-primary primary 1 1 1 0
Instances status
Name Current LSN Replication role Status QoS Manager Version Node
---- ----------- ---------------- ------ --- --------------- ----
sandbox-1 0/6053720 Primary OK BestEffort 1.30.1 k8s-eu-worker
sandbox-2 0/6053720 Standby (async) OK BestEffort 1.30.1 k8s-eu-worker2
sandbox-3 0/6053720 Standby (async) OK BestEffort 1.30.1 k8s-eu-worker
추가 -v(예: kubectl cnpg status sandbox -v -v)로 PostgreSQL 구성, HBA 설정, 인증서도 볼 수 있어요.
이 명령은 yaml과 json 형식의 출력도 지원해요.
:::note
status 명령은 pod 파일 시스템에 접근하는 작업을 실행해요. 예를 들어 클러스터 크기를 계산하는 du, 구성 파일을 읽는 cat 등이요. 데이터 볼륨이 큰(예: 1TB 이상) 클러스터에서는 이 작업들이 기본 타임아웃 10초보다 오래 걸릴 수 있어요. --timeout 플래그로 타임아웃을 조정할 수 있어요 (예: kubectl cnpg status sandbox --timeout 45s).
:::
승격 (Promote)
이 명령의 의미는 클러스터의 pod를 프라이머리로 promote하여, 유지보수 작업을 시작하거나 클러스터의 스위치오버 상황을 테스트할 수 있게 하는 것이에요:
kubectl cnpg promote CLUSTER CLUSTER-INSTANCE
또는 인스턴스 노드 번호로 승격할 수 있어요:
kubectl cnpg promote CLUSTER INSTANCE
인증서 (Certificates)
CloudNativePG 연산자로 만든 클러스터는 CA와 함께 동작해 TLS 인증 인증서를 서명해요.
인증서를 얻으려면 자격 증명을 저장할 시크릿의 이름, 클러스터 이름, 이 인증서용 사용자를 제공해야 해요:
kubectl cnpg certificate cluster-cert --cnpg-cluster CLUSTER --cnpg-user USER
시크릿이 생성된 후 kubectl로 가져올 수 있어요:
kubectl get secret cluster-cert
그리고 같은 내용을 평문으로 다음 명령으로 볼 수 있어요:
kubectl get secret cluster-cert -o json | jq -r '.data | map(@base64d) | .[]'
재시작 (Restart)
kubectl cnpg restart 명령은 두 경우에 사용할 수 있어요:
-
특정 클러스터의 롤아웃 재시작을 연산자가 오케스트레이션하도록 요청. 이는 커스텀 모니터링 쿼리를 담은
ConfigMaps같은 클러스터 의존 객체에 구성 변경을 적용하는 데 유용해요. -
단일 인스턴스 재시작 요청. 인스턴스가 클러스터의 프라이머리면 인플레이스로, 레플리카면 pod를 삭제·재생성하는 방식이에요.
# this command will restart a whole cluster in a rollout fashion
kubectl cnpg restart CLUSTER
# this command will restart a single instance, according to the policy above
kubectl cnpg restart CLUSTER INSTANCE
인플레이스 재시작이 요청됐지만 스위치오버 없이는 변경을 적용할 수 없으면, 스위치오버가 인플레이스 재시작보다 우선해요. 일반적인 예가 PostgreSQL 이미지의 마이너 업그레이드예요.
:::note
ConfigMaps와 Secrets를 인스턴스가 자동으로 리로드하게 하려면, 키가 cnpg.io/reload인 레이블을 추가하면 돼요.
:::
리로드 (Reload)
kubectl cnpg reload 명령은 특정 클러스터의 리컨실레이션 루프를 트리거하도록 연산자에게 요청해요. 이는 커스텀 모니터링 쿼리를 담은 ConfigMaps 같은 클러스터 의존 객체에 구성 변경을 적용하는 데 유용해요.
다음 명령은 주어진 클러스터의 모든 구성을 리로드해요:
kubectl cnpg reload CLUSTER
유지보수 (Maintenance)
kubectl cnpg maintenance 명령은 네임스페이스 전반에 걸쳐 하나 이상의 클러스터를 수정하고 유지보수 창 값을 설정하는 데 도움을 줘요. 다음 필드를 변경해요:
.spec.nodeMaintenanceWindow.inProgress.spec.nodeMaintenanceWindow.reusePVC
인자로 set과 unset을 받으며, set이면 inProgress를 true로, unset이면 false로 설정해요.
기본적으로 --reusePVC 플래그를 전달하지 않으면 reusePVC는 항상 false로 설정돼요.
플러그인은 수정할 클러스터 목록과 새 값으로 확인을 요청하며, 수락되면 목록의 모든 클러스터에 이 작업이 적용돼요.
Kubernetes 클러스터의 모든 PostgreSQL을 유지보수로 설정하려면 다음 명령을 쓰면 돼요:
kubectl cnpg maintenance set --all-namespaces
그러면 갱신할 모든 클러스터 목록이 나와요:
The following are the new values for the clusters
Namespace Cluster Name Maintenance reusePVC
--------- ------------ ----------- --------
default cluster-example true false
default pg-backup true false
test cluster-example true false
Do you want to proceed? [y/n]: y
보고서 (Report)
kubectl cnpg report 명령은 다양한 정보를 ZIP 파일로 묶어요. 프로덕션에서 클러스터 문제를 디버깅하는 데 필요한 컨텍스트를 제공하는 것이 목적이에요.
operator와 cluster 두 개의 서브커맨드가 있어요.
report Operator
operator 서브커맨드는 연산자 배포, 구성, 이벤트에 관한 정보를 제공하도록 연산자에게 요청해요.
:::info[Important]
Secrets와 ConfigMaps의 모든 기밀 정보는 REDACTED(수정)돼요. Data 맵은 키를 보여주지만 값은 비어 있어요. -S/--stopRedaction 플래그는 수정을 무효화하고 값을 보여줘요. 사용 시 스스로 책임지세요. 이는 개인 데이터를 공유하게 됩니다.
:::
:::note
기본적으로 연산자 로그는 수집되지 않지만, --logs 플래그로 연산자 로그 수집을 활성화할 수 있어요.
:::
:::info[최소 권한 지원 (Least-Privilege Support)]
report operator 명령은 최소 권한으로 동작해요. 연산자 배포만 필수이며, 다른 모든 리소스는 선택 사항이고 best-effort 기준으로 수집돼요. 특정 리소스(예: webhooks, OLM 리소스)에 대한 권한이 없으면 경고가 로깅되고 사용 가능한 데이터로 보고서 생성을 계속해요.
:::
보고서에는 다음이 포함돼요:
- 배포 정보 (필수): 연산자
Deployment - 연산자 pod (선택): 연산자
Pod정보 - 구성 (선택): 연산자 네임스페이스의
Secrets와ConfigMaps - 이벤트 (선택): 연산자 네임스페이스의
Events - webhook 구성 (선택): mutating·validating webhook 구성 (클러스터 범위)
- webhook 서비스 (선택): webhook 서비스
- OLM 리소스 (선택): subscriptions, cluster service versions, install plans (OLM이 설치된 경우)
- 로그 (선택): JSON-lines 형식의 연산자
Pod로그 (--logs플래그 필요)
:::warning[최소 권한 (Minimal permissions)]
연산자 네임스페이스의 연산자 배포에 대한 읽기 접근(get). 이를 통해 네임스페이스 범위 사용자가 기본 트러블슈팅 보고서를 생성할 수 있어요.
:::
:::info[전체 보고서를 위한 권장 권한 (Recommended permissions for full report)]
pods, events에 대한 list; secrets, configmaps, services에 대한 get (네임스페이스 범위); webhook 구성에 대한 list (클러스터 범위)를 추가하세요.
:::
네임스페이스 범위 권한만 있는 사용자도 유용한 보고서를 생성할 수 있어요:
# With only deployment read access
kubectl cnpg report operator -n cnpg-system -f report.zip
:::info 이 명령은 접근할 수 없는 리소스에 대해 경고를 로깅하지만, 배포 매니페스트와 함께 보고서를 성공적으로 생성해요. 이는 기본 트러블슈팅에 종종 충분해요. :::
이 명령은 YAML 형식(기본값, -o 플래그로 JSON 설정 가능)의 다양한 매니페스트를 담은 ZIP 파일을 생성해요. -f 플래그로 결과 파일 이름을 명시하세요. -f 플래그를 사용하지 않으면 zip 파일에 기본 타임스탬프 파일 이름이 생성돼요.
:::note
보고서 플러그인은 kubectl 관례를 따르며, 네임스페이스로 제한된 객체를 찾아요. CNPG 연산자는 일반적으로 클러스터와 같은 네임스페이스에 설치되지 않아요. 예를 들어 기본 설치 네임스페이스는 cnpg-system이에요.
:::
kubectl cnpg report operator -n cnpg-system
결과:
Successfully written report to "report_operator_<TIMESTAMP>.zip" (format: "yaml")
-f 플래그로:
kubectl cnpg report operator -n cnpg-system -f reportRedacted.zip
파일을 압축 풀면 디렉터리를 깔끔하게 유지하기 위해 타임스탬프가 붙은 최상위 폴더가 생성돼요:
unzip reportRedacted.zip
결과:
Archive: reportRedacted.zip
creating: report_operator_<TIMESTAMP>/
creating: report_operator_<TIMESTAMP>/manifests/
inflating: report_operator_<TIMESTAMP>/manifests/deployment.yaml
inflating: report_operator_<TIMESTAMP>/manifests/operator-pod.yaml
inflating: report_operator_<TIMESTAMP>/manifests/events.yaml
inflating: report_operator_<TIMESTAMP>/manifests/validating-webhook-configuration.yaml
inflating: report_operator_<TIMESTAMP>/manifests/mutating-webhook-configuration.yaml
inflating: report_operator_<TIMESTAMP>/manifests/webhook-service.yaml
inflating: report_operator_<TIMESTAMP>/manifests/cnpg-ca-secret(secret).yaml
inflating: report_operator_<TIMESTAMP>/manifests/cnpg-webhook-cert(secret).yaml
--logs 옵션을 활성화했다면 추가 하위 디렉터리가 보일 거예요:
Archive: report_operator_<TIMESTAMP>.zip
<snipped …>
creating: report_operator_<TIMESTAMP>/operator-logs/
inflating: report_operator_<TIMESTAMP>/operator-logs/cnpg-controller-manager-66fb98dbc5-pxkmh-logs.jsonl
:::note 플러그인은 이전 연산자의 로그를 가져오려 시도하는데, 이는 재시작된 연산자를 조사할 때 유용해요. 모든 경우에 현재 연산자 로그도 가져오려 시도해요. 현재와 이전 로그 모두 사용 가능하면 둘 다 보여줘요. :::
====== Beginning of Previous Log =====
2023-03-28T12:56:41.251711811Z {"level":"info","ts":"2023-03-28T12:56:41Z","logger":"setup","msg":"Starting CloudNativePG Operator","version":"1.30.1","build":{"Version":"1.30.1+dev107","Commit":"cc9bab17","Date":"2023-03-28"}}
2023-03-28T12:56:41.251851909Z {"level":"info","ts":"2023-03-28T12:56:41Z","logger":"setup","msg":"Starting pprof HTTP server","addr":"0.0.0.0:6060"}
<snipped …>
====== End of Previous Log =====
2023-03-28T12:57:09.854306024Z {"level":"info","ts":"2023-03-28T12:57:09Z","logger":"setup","msg":"Starting CloudNativePG Operator","version":"1.30.1","build":{"Version":"1.30.1+dev107","Commit":"cc9bab17","Date":"2023-03-28"}}
2023-03-28T12:57:09.854363943Z {"level":"info","ts":"2023-03-28T12:57:09Z","logger":"setup","msg":"Starting pprof HTTP server","addr":"0.0.0.0:6060"}
연산자가 재시작되지 않았다면 ====== Begin …과 ====== End … 가드가 내용 없이 계속 보일 거예요.
기밀 정보가 기본적으로 REDACTED인지 확인할 수 있어요:
cd report_operator_<TIMESTAMP>/manifests/
head cnpg-ca-secret\(secret\).yaml
data:
ca.crt: ""
ca.key: ""
metadata:
creationTimestamp: "2022-03-22T10:42:28Z"
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
-S(--stopRedaction) 옵션을 활성화하면 시크릿이 보여요:
kubectl cnpg report operator -n cnpg-system -f reportNonRedacted.zip -S
기밀 정보를 보려 한다는 알림이 나와요:
WARNING: secret Redaction is OFF. Use it with caution
Successfully written report to "reportNonRedacted.zip" (format: "yaml")
unzip reportNonRedacted.zip
head cnpg-ca-secret\(secret\).yaml
data:
ca.crt: LS0tLS1CRUdJTiBD…
ca.key: LS0tLS1CRUdJTiBF…
metadata:
creationTimestamp: "2022-03-22T10:42:28Z"
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
report Cluster
cluster 서브커맨드는 다음을 수집해요:
- 클러스터 리소스:
kubectl get cluster -o yaml과 동일한 클러스터 정보 - 클러스터 pods: 클러스터 네임스페이스에서 클러스터 이름과 일치하는 pods
- 클러스터 jobs: 클러스터 네임스페이스에서 클러스터 이름과 일치하는 jobs(있으면)
- 이벤트: 클러스터 네임스페이스의 이벤트
- pod 로그: 클러스터 Pod의 로그 (선택, 기본 꺼짐) JSON-lines 형식
- job 로그: jobs가 만든 Pod의 로그 (선택, 기본 꺼짐) JSON-lines 형식
cluster 서브커맨드는 operator처럼 -f와 -o 플래그를 받아요. -f 플래그를 사용하지 않으면 기본 타임스탬프 보고서 이름이 사용돼요. 클러스터 정보는 구성 Secrets/ConfigMaps를 포함하지 않으므로 -S는 비활성화돼요.
:::note
기본적으로 클러스터 로그는 수집되지 않지만, --logs 플래그로 클러스터 로그 수집을 활성화할 수 있어요.
:::
사용법:
kubectl cnpg report cluster CLUSTER [flags]
operator 서브커맨드와 달리, cluster 서브커맨드에서는 클러스터 이름을 제공해야 하고, 클러스터가 기본 네임스페이스에 없으면 네임스페이스도 매우 확실히 제공해야 한다는 점을 알아두세요.
kubectl cnpg report cluster CLUSTER -f report.zip [-n NAMESPACE]
그 다음:
unzip report.zip
Archive: report.zip
creating: report_cluster_example_<TIMESTAMP>/
creating: report_cluster_example_<TIMESTAMP>/manifests/
inflating: report_cluster_example_<TIMESTAMP>/manifests/cluster.yaml
inflating: report_cluster_example_<TIMESTAMP>/manifests/cluster-pods.yaml
inflating: report_cluster_example_<TIMESTAMP>/manifests/cluster-jobs.yaml
inflating: report_cluster_example_<TIMESTAMP>/manifests/events.yaml
--logs 플래그로 pod와 job 로그를 ZIP에 추가할 수 있다는 걸 기억하세요.
kubectl cnpg report cluster CLUSTER [-n NAMESPACE] --logs
결과:
Successfully written report to "report_cluster_example_<TIMESTAMP>.zip" (format: "yaml")
unzip report_cluster_<TIMESTAMP>.zip
Archive: report_cluster_example_<TIMESTAMP>.zip
creating: report_cluster_example_<TIMESTAMP>/
creating: report_cluster_example_<TIMESTAMP>/manifests/
inflating: report_cluster_example_<TIMESTAMP>/manifests/cluster.yaml
inflating: report_cluster_example_<TIMESTAMP>/manifests/cluster-pods.yaml
inflating: report_cluster_example_<TIMESTAMP>/manifests/cluster-jobs.yaml
inflating: report_cluster_example_<TIMESTAMP>/manifests/events.yaml
creating: report_cluster_example_<TIMESTAMP>/logs/
inflating: report_cluster_example_<TIMESTAMP>/logs/cluster-example-full-1.jsonl
creating: report_cluster_example_<TIMESTAMP>/job-logs/
inflating: report_cluster_example_<TIMESTAMP>/job-logs/cluster-example-full-1-major-upgrade-qnnvw.jsonl
로그 (Logs)
kubectl cnpg logs 명령은 CloudNativePG 관련 pod 묶음의 로그를 한 번에 따라볼 수 있게 해줘요.
현재 사용 가능한 서브커맨드가 하나 있어요: cluster.
클러스터 로그 (Cluster logs)
cluster 서브커맨드는 클러스터의 모든 pod 로그를 단일 스트림이나 파일로 모아요. 즉 명령의 단일 호출로 모든 pod 로그를 단일 터미널 창에서 얻을 수 있어요.
모든 cnpg 플러그인 서브커맨드에서처럼 -h 플래그로 지침과 도움말을 얻을 수 있어요:
kubectl cnpg logs cluster -h
logs 명령은 --timestamps 플래그를 사용하지 않는 한 JSON-lines 형식으로 로그를 표시해요. 그 경우 사람이 읽을 수 있는 타임스탬프가 각 줄에 앞에 붙어요. 이 경우 줄은 더 이상 유효한 JSON이 아니므로 jq 같은 도구가 원하는 대로 동작하지 않을 수 있어요.
logs cluster 서브커맨드에 -f 플래그(일명 --follow)를 주면 클러스터 pod 로그를 따라가고, 명령이 호출된 후 클러스터에서 생성되는 새 pod도 지켜봐요. 재시작되거나 재생성된 pod를 포함해 발견된 새 pod의 로그도 따라가요. 로그는 터미널의 표준 출력에 표시돼요. 이 명령은 클러스터에 pod가 더 이상 없거나 사용자가 중단할 때만 종료돼요.
logs를 -f 옵션 없이 호출하면 호출 시점까지의 모든 클러스터 pod 로그를 읽어 터미널 표준 출력에 표시한 다음 종료해요. -o 또는 --output 플래그를 제공해 표준 출력 대신 로그가 저장될 파일 이름을 지정할 수 있어요. --tail 플래그는 클러스터의 각 pod에서 가져올 로그 줄 수를 지정하는 데 사용해요. 기본적으로 logs cluster 서브커맨드는 클러스터의 각 pod에서 모든 로그를 표시해요. "follow" 플래그 -f와 결합하면, --tail이 지정한 로그 수를 현재 시점까지 가져오고, 그 후에는 새 로그를 따라가요.
참고: 다른 cnpg 플러그인 명령과 달리 -f는 파일 지정이 아니라 "follow"를 뜻해요. 이는 kubectl logs의 관례, 즉 -f가 로그를 따라가야 함을 의미하는 관례와 일치해요.
사용법:
kubectl cnpg logs cluster CLUSTER [flags]
-f 옵션으로 따라가기:
kubectl cnpg report cluster CLUSTER -f
--tail 옵션으로 각 pod에서 3줄을 표시하고 -f 옵션으로 따라가기:
kubectl cnpg report cluster CLUSTER -f --tail 3
{"level":"info","ts":"2023-06-30T13:37:33Z","logger":"postgres","msg":"2023-06-30 13:37:33.142 UTC [26] LOG: ending log output to stderr","source":"/controller/log/postgres","logging_pod":"cluster-example-3"}
{"level":"info","ts":"2023-06-30T13:37:33Z","logger":"postgres","msg":"2023-06-30 13:37:33.142 UTC [26] HINT: Future log output will go to log destination \"csvlog\".","source":"/controller/log/postgres","logging_pod":"cluster-example-3"}
…
…
-o 옵션을 생략하고 --output을 지정하면:
$ kubectl cnpg logs cluster CLUSTER --output my-cluster.log
Successfully written logs to "my-cluster.log"
Pretty
pretty 서브커맨드는 표준 입력에서 로그 스트림을 읽어 사람이 읽을 수 있는 출력으로 형식화하고, 타임스탬프별로 항목을 정렬하려 시도해요.
kubectl cnpg logs cluster와 함께 사용할 수 있어요. 다음 예시처럼:
$ kubectl cnpg logs cluster cluster-example | kubectl cnpg logs pretty
2024-10-15T17:35:00.336 INFO cluster-example-1 instance-manager Starting CloudNativePG Instance Manager
2024-10-15T17:35:00.336 INFO cluster-example-1 instance-manager Checking for free disk space for WALs before starting PostgreSQL
2024-10-15T17:35:00.347 INFO cluster-example-1 instance-manager starting tablespace manager
2024-10-15T17:35:00.347 INFO cluster-example-1 instance-manager starting external server manager
[...]
또는 stern이나 kubectl logs처럼 JSON 형식의 CNPG 로그를 만드는 다른 명령과 함께 사용할 수 있어요. 다음 예시처럼:
$ kubectl logs cluster-example-1 | kubectl cnpg logs pretty
2024-10-15T17:35:00.336 INFO cluster-example-1 instance-manager Starting CloudNativePG Instance Manager
2024-10-15T17:35:00.336 INFO cluster-example-1 instance-manager Checking for free disk space for WALs before starting PostgreSQL
2024-10-15T17:35:00.347 INFO cluster-example-1 instance-manager starting tablespace manager
2024-10-15T17:35:00.347 INFO cluster-example-1 instance-manager starting external server manager
[...]
pretty 서브커맨드는 고급 로그 필터링도 지원해, 사용자가 특정 pod나 로거의 로그를 표시하거나 심각도 수준으로 로그를 필터링할 수 있어요. 예:
$ kubectl cnpg logs cluster cluster-example | kubectl cnpg logs pretty --pods cluster-example-1 --loggers postgres --log-level info
2024-10-15T17:35:00.509 INFO cluster-example-1 postgres 2024-10-15 17:35:00.509 UTC [29] LOG: redirecting log output to logging collector process
2024-10-15T17:35:00.509 INFO cluster-example-1 postgres 2024-10-15 17:35:00.509 UTC [29] HINT: Future log output will appear in directory "/controller/log"...
2024-10-15T17:35:00.510 INFO cluster-example-1 postgres 2024-10-15 17:35:00.509 UTC [29] LOG: ending log output to stderr
2024-10-15T17:35:00.510 INFO cluster-example-1 postgres ending log output to stderr
[...]
pretty 서브커맨드는 로그 스트림을 정렬해, 로그를 더 쉽게 추론할 수 있게 해줘요. 이를 위해 로그를 그룹으로 모으고 그룹 안에서 타임스탬프별로 정렬해요. pretty는 "follow" 모드의 명령에서 파이프될 수 있으므로 이것이 대화형으로 정렬하는 유일한 방법이에요. 서브커맨드는 각 정렬된 그룹 끝에 그룹 구분선 ---을 추가해요. 그룹 크기는 --sorting-group-size 플래그(기본값: 1000)로 구성할 수 있어요. 다음 예시와 같아요:
$ kubectl cnpg logs cluster cluster-example | kubectl cnpg logs pretty --sorting-group-size=3
2024-10-15T17:35:20.426 INFO cluster-example-2 instance-manager Starting CloudNativePG Instance Manager
2024-10-15T17:35:20.426 INFO cluster-example-2 instance-manager Checking for free disk space for WALs before starting PostgreSQL
2024-10-15T17:35:20.438 INFO cluster-example-2 instance-manager starting tablespace manager
---
2024-10-15T17:35:20.438 INFO cluster-example-2 instance-manager starting external server manager
2024-10-15T17:35:20.438 INFO cluster-example-2 instance-manager starting controller-runtime manager
2024-10-15T17:35:20.439 INFO cluster-example-2 instance-manager Starting EventSource
---
[...]
모든 사용 가능한 옵션을 탐색하려면 -h 플래그를 사용해 지원되는 플래그와 사용법에 대한 자세한 설명을 확인하세요.
:::info
-v 옵션을 더 추가하면 로그의 상세도를 높일 수도 있어요.
:::
파괴 (Destroy)
kubectl cnpg destroy 명령은 인스턴스와 관련된 모든 PVC를 Kubernetes 클러스터에서 제거하는 데 도움을 줘요.
선택 --keep-pvc 플래그를 지정하면 PVC를 유지하면서, 인스턴스가 설정한 모든 metadata.ownerReferences를 제거할 수 있어요. 또한 PVC의 cnpg.io/pvcStatus 레이블은 더 이상 사용되지 않음을 나타내기 위해 ready에서 detached로 변경돼요.
--keep-pvc 플래그 없이 명령을 다시 실행하면 detached PVC가 제거돼요.
사용법:
kubectl cnpg destroy CLUSTER INSTANCE
다음 예시는 cluster-example-2 pod와 관련 PVC를 제거해요:
kubectl cnpg destroy cluster-example 2
클러스터 하이버네이션 (Cluster Hibernation)
때로는 CloudNativePG Cluster를 데이터를 보존하면서 일시적으로 중단해, 나중에 운영을 재개해야 할 때가 있어요. 이 기능을 클러스터 하이버네이션이라고 해요.
하이버네이션은 cnpg.io/hibernation 어노테이션을 사용해 선언적으로 관리돼요.
:::info 자세한 내용은 "Declarative Hibernation" 문서 페이지를 참조하세요. :::
과정을 단순화하기 위해 kubectl용 cnpg 플러그인은 어노테이션을 적용하는 편리한 단축키 역할을 하는 hibernate 명령을 제공해요.
클러스터를 하이버네이션하려면 다음을 실행하세요:
kubectl cnpg hibernate on CLUSTER
이 명령은 클러스터에 cnpg.io/hibernation=on 어노테이션을 적용해 그 실행을 중단해요.
하이버네이션된 클러스터를 재개하려면:
kubectl cnpg hibernate off CLUSTER
이는 cnpg.io/hibernation=off를 설정해 하이버네이션 상태를 제거해요.
클러스터 상태는 언제든 확인할 수 있어요:
kubectl cnpg status CLUSTER
이는 하이버네이션 여부를 포함한 클러스터의 현재 상태를 표시해요.
pgbench로 데이터베이스 벤치마킹 (Benchmarking the database with pgbench)
Pgbench는 다음 명령으로 기존 PostgreSQL 클러스터에 대해 실행할 수 있어요:
kubectl cnpg pgbench CLUSTER -- --time 30 --client 1 --jobs 1
자세한 내용은 Benchmarking pgbench 섹션을 참조하세요.
fio로 스토리지 벤치마킹 (Benchmarking the storage with fio)
fio는 다음 명령으로 기존 스토리지 클래스에 대해 실행할 수 있어요:
kubectl cnpg fio FIO_JOB_NAME [-n NAMESPACE]
자세한 내용은 Benchmarking fio 섹션을 참조하세요.
새 물리 백업 요청 (Requesting a new physical backup)
kubectl cnpg backup 명령은 새 Backup 리소스를 만들어 기존 Postgres 클러스터의 새 물리 백업을 요청해요.
다음 예시는 주어진 클러스터의 온디맨드 백업을 요청해요:
kubectl cnpg backup CLUSTER
또는 volume snapshot을 사용한다면:
kubectl cnpg backup CLUSTER -m volumeSnapshot
생성된 백업은 요청 시간에 따라 이름이 지어져요:
$ kubectl cnpg backup cluster-example
backup/cluster-example-20230121002300 created
기본적으로 새로 생성된 백업은 클러스터에 정의된 백업 대상 정책을 사용해 어떤 인스턴스에서 실행할지 선택해요. 그러나 --backup-target 옵션으로 이 정책을 오버라이드할 수 있어요.
Volume snapshot 백업의 경우 --online 옵션으로 온라인/핫 백업 또는 오프라인/콜드 백업을 요청할 수도 있어요. 또한 --immediate-checkpoint와 --wait-for-archive 옵션을 명시적으로 설정해 온라인 백업을 튜닝할 수 있어요.
--dry-run 옵션으로 생성될 Backup 리소스를 미리 볼 수 있어요. API 서버에는 실제로 제출하지 않아요:
kubectl cnpg backup CLUSTER --dry-run
"Backup" 섹션에 구성 설정에 대한 더 많은 정보가 있어요.
psql 실행 (Launching psql)
kubectl cnpg psql CLUSTER 명령은 실제 pod에서 실행하는 것처럼 기존 Postgres 클러스터에 연결된 새 PostgreSQL 대화형 프론트엔드 프로세스(psql)를 시작해요. 즉 postgres 사용자를 사용하고 postgres 데이터베이스에 연결한다는 뜻이에요.
:::info[Important]
postgres 사용자로 연결하므로, 프로덕션 환경에서는 이 방법을 극도로 주의해서, 권한 있는 담당자만 사용해야 해요.
:::
$ kubectl cnpg psql cluster-example
psql (18.6 (Debian 18.6-1.pgdg110+1))
Type "help" for help.
postgres=#
기본적으로 이 명령은 프라이머리 인스턴스에 연결해요. --replica 옵션으로 레플리카에 대해 작업하도록 선택할 수 있어요:
$ kubectl cnpg psql --replica cluster-example
psql (18.6 (Debian 18.6-1.pgdg110+1))
Type "help" for help.
postgres=# select pg_is_in_recovery();
pg_is_in_recovery
-------------------
t
(1 row)
postgres=# \q
이 명령은 kubectl exec를 시작하며, 올바르게 동작하려면 kubectl 실행 파일이 PATH 변수에서 접근 가능해야 해요.
기본적으로 postgres 데이터베이스가 사용돼요. -- 구분자 뒤에 psql이 지원하는 모든 옵션을 전달할 수 있어요. 예를 들어 특정 데이터베이스에 연결하려면:
$ kubectl cnpg psql cluster-example -- app
psql (18.6 (Debian 18.6-1.pgdg110+1))
Type "help" for help.
app=#
또한 psql 옵션 -c로 쿼리를 직접 실행할 수도 있어요.
$ kubectl cnpg psql cluster-example -- -c "SELECT pg_is_in_recovery();"
pg_is_in_recovery
-------------------
f
(1 row)
Postgres 클러스터 스냅샷 (Snapshotting a Postgres cluster)
:::warning
kubectl cnpg snapshot 명령이 제거됐어요.
volume snapshot을 사용한 백업을 요청하려면 backup 명령을 사용하세요.
:::
평가/시연 목적으로만 pgAdmin4 사용 (Using pgAdmin4 for evaluation/demonstration purposes only)
pgAdmin은 PostgreSQL을 위한 가장 인기 있고 기능이 풍부한 오픈소스 관리·개발 플랫폼이에요. 프로젝트에 대한 자세한 내용은 공식 문서를 참조하세요.
pgAdmin 개발 팀이 공식 Docker 컨테이너 이미지를 유지 관리하므로, pgAdmin을 표준 Kubernetes 배포로 환경에 설치할 수 있어요.
:::info[Important] Kubernetes 프로덕션 환경에서의 pgAdmin 배포는 이 문서의 범위를 넘어서며, 더 넓게 CloudNativePG 프로젝트의 범위도 넘어서요. :::
그러나 시연과 평가 목적으로, CloudNativePG는 적합한 솔루션을 제공해요. cnpg 플러그인은 pgadmin4 명령을 구현해, 주어진 데이터베이스 Cluster에 연결하고 kind 같은 로컬 환경에서 그 내용을 탐색하는 간단한 방법을 제공해요.
예를 들어 cluster-example 클러스터용 pgAdmin4 데모 배포를 다음과 같이 설치할 수 있어요:
kubectl cnpg pgadmin4 cluster-example
이 명령은 다음을 생성해요:
ConfigMap/cluster-example-pgadmin4 created
Deployment/cluster-example-pgadmin4 created
Service/cluster-example-pgadmin4 created
Secret/cluster-example-pgadmin4 created
[...]
pgAdmin을 배포한 후 kubectl로 포트를 포워딩하고 화면의 지침에 따라 브라우저를 통해 연결하세요.

평소처럼 --dry-run 옵션으로 YAML 파일을 생성할 수 있어요:
kubectl cnpg pgadmin4 --dry-run cluster-example
pgAdmin4는 데스크톱 또는 서버 모드로 설치할 수 있으며, 기본값은 서버예요.
server 모드에서는 무작위로 생성된 비밀번호로 인증이 필요하고, 사용자가 연결할 데이터베이스를 수동으로 지정해야 해요.
반면 desktop 모드는 인증 없이 pgAdmin 웹 인터페이스를 시작해요. app 사용자로 app 데이터베이스에 자동으로 연결하므로, kind를 사용한 로컬 배포 같은 빠른 데모에 이상적이에요:
kubectl cnpg pgadmin4 --mode desktop cluster-example
데모를 마친 후 pgAdmin 배포를 종료하려면 다음을 실행하세요:
kubectl cnpg pgadmin4 --dry-run cluster-example | kubectl delete -f -
:::warning 프로덕션에서 플러그인으로 pgAdmin을 절대 배포하지 마세요. :::
논리 복제 Publication (Logical Replication Publications)
cnpg publication 명령 그룹은 PostgreSQL 논리 복제 publication의 생성과 제거를 간소화하도록 설계됐어요. 이 명령들은 주로 논리 복제 publication 생성, 특히 원격 PostgreSQL 데이터베이스에서 생성을 돕기 위한 것임을 알아두세요.
:::warning 이 명령들을 사용하기 전에 PostgreSQL 네이티브 논리 복제 시스템의 능력과 제한을 모두 확실히 이해하는 것이 중요해요. 특히 논리 복제 제한사항에 주의하세요. :::
새 publication 생성 (Creating a new publication)
논리 복제 publication을 만들려면 cnpg publication create 명령을 사용해요. 이 명령의 기본 구조는 다음과 같아요:
kubectl cnpg publication create \
--publication PUBLICATION_NAME \
[--external-cluster EXTERNAL_CLUSTER]
LOCAL_CLUSTER [options]
두 가지 주요 사용 사례가 있어요:
-
--external-cluster포함: 이 옵션을 사용해 외부 클러스터(즉externalClusters스탠자에 정의된)에 publication을 만들어요. 명령은LOCAL_CLUSTER에서 발행되지만, publication은EXTERNAL_CLUSTER의 데이터를 위한 것이에요. -
--external-cluster없이: 이 옵션을 사용해LOCAL_CLUSTERPostgreSQLCluster(기본적으로app데이터베이스)에 publication을 만들어요.
:::warning
외부 클러스터에 연결할 때 지정된 사용자가 CREATE PUBLICATION 명령을 실행할 충분한 권한을 가졌는지 확인하세요.
:::
CREATE PUBLICATION 명령과 유사한 여러 옵션이 있어, 복제할 테이블 그룹을 정의할 수 있어요. 주목할 만한 옵션:
--all-tables옵션을 지정하면FOR ALL TABLESpublication을 만들어요.- 또는 다음을 여러 번 지정할 수 있어요:
--table: publication에 특정 테이블(표현식 포함) 추가--schema: 지정된 데이터베이스 스키마의 모든 테이블 포함 (PostgreSQL 15부터 사용 가능)
--dry-run 옵션으로 플러그인이 실행할 SQL 명령을 미리 볼 수 있어요.
추가 정보와 상세 지침은 다음 명령을 입력하세요:
kubectl cnpg publication create --help
예시 (Example)
source-cluster와 destination-cluster가 있다고 할 때, source-cluster의 데이터에 대한 publication을 만들고 싶어요. destination-cluster는 externalClusters 스탠자에 source-cluster를 가리키는 항목이 있어요.
다음을 실행할 수 있어요:
kubectl cnpg publication create destination-cluster \
--external-cluster=source-cluster --all-tables
이는 destination-cluster에서 SQL 명령을 실행하면서 source-cluster의 모든 테이블에 대한 publication을 만들어요.
또는 다음을 실행할 수도 있어요:
kubectl cnpg publication create source-cluster \
--publication=app --all-tables
이는 원본 클러스터에서 SQL 명령을 실행하면서 source-cluster의 모든 테이블에 대해 app이라는 이름의 publication을 만들어요.
:::info 설명과 영감을 위해 두 개의 샘플 파일이 제공돼요: logical-source와 logical-destination. :::
publication 제거 (Dropping a publication)
cnpg publication drop 명령은 publication 이름, 클러스터 이름, 선택 외부 클러스터 등 유사한 핵심 옵션을 제공하며 create 명령을 매끄럽게 보완해요. 다음 명령 구조로 PUBLICATION을 드롭할 수 있어요:
kubectl cnpg publication drop \
--publication PUBLICATION_NAME \
[--external-cluster EXTERNAL_CLUSTER]
LOCAL_CLUSTER [options]
더 많은 세부 사항과 정확한 지침을 보려면 다음 명령을 사용하세요:
kubectl cnpg publication drop --help
논리 복제 Subscription (Logical Replication Subscriptions)
cnpg subscription 명령 그룹은 PostgreSQL 논리 복제 subscription의 생성과 제거를 단순화하도록 설계된 전용 명령 집합이에요. 이 명령들은 특히 원격 PostgreSQL 데이터베이스를 다룰 때 논리 복제 subscription 설정을 돕도록 특별히 제작됐어요.
:::warning 이 명령들을 사용하기 전에 PostgreSQL 네이티브 논리 복제 시스템의 능력과 제한을 모두 종합적으로 이해하는 것이 필수적이에요. 특히 논리 복제 제한사항에 주의하세요. :::
subscription 관리 외에도, 원본 클러스터에서 모든 시퀀스를 동기화하는 유용한 명령을 제공해요. 적용 가능성은 다양할 수 있지만, 이 명령은 메이저 업그레이드나 원격 서버에서의 데이터 가져오기를 포함하는 시나리오에서 특히 유용할 수 있어요.
새 subscription 생성 (Creating a new subscription)
논리 복제 subscription을 만들려면 cnpg subscription create 명령을 사용해요. 이 명령의 기본 구조는 다음과 같아요:
kubectl cnpg subscription create \
--subscription SUBSCRIPTION_NAME \
--publication PUBLICATION_NAME \
--external-cluster EXTERNAL_CLUSTER \
LOCAL_CLUSTER [options]
이 명령은 LOCAL_CLUSTER의 externalClusters 스탠자에 정의된 지정 외부 클러스터의 지정 publication을 향하는 subscription을 구성해요.
추가 정보와 상세 지침은 다음 명령을 입력하세요:
kubectl cnpg subscription create --help
예시 (Example)
publication 섹션에서처럼, source-cluster와 destination-cluster가 있고 이미 app이라는 publication을 만들었어요.
다음 명령:
kubectl cnpg subscription create destination-cluster \
--external-cluster=source-cluster \
--publication=app --subscription=app
대상 클러스터에 app용 subscription을 만들어요.
:::warning 프로덕션 환경에 구현하기 전에 비-프로덕션 환경에서 subscription을 우선 테스트해, 그 효과를 보장하고 잠재적 문제를 식별하세요. :::
:::info 설명과 영감을 위해 두 개의 샘플 파일이 제공돼요: logical-source와 logical-destination. :::
subscription 제거 (Dropping a subscription)
cnpg subscription drop 명령은 create 명령을 매끄럽게 보완해요. 다음 명령 구조로 SUBSCRIPTION을 드롭할 수 있어요:
kubectl cnpg subcription drop \
--subscription SUBSCRIPTION_NAME \
LOCAL_CLUSTER [options]
더 많은 세부 사항과 정확한 지침을 보려면 다음 명령을 사용하세요:
kubectl cnpg subscription drop --help
시퀀스 동기화 (Synchronizing sequences)
publication과 subscription을 통해 구현되는 PostgreSQL 논리 복제의 주목할 만한 제약 중 하나는 시퀀스 동기화가 없다는 점이에요. 이는 특히 더 높은 PostgreSQL 버전으로의 라이브 데이터베이스 마이그레이션에 논리 복제를 사용할 때 관련이 있어요. 이 과정의 중요한 단계는 애플리케이션을 새 데이터베이스로 전환하기(cutover) 전에 시퀀스를 갱신하는 것이에요.
이 제한을 해결하기 위해 cnpg subscription sync-sequences 명령이 해결책을 제공해요. 이 명령은 원본 데이터베이스에 연결해 모든 관련 시퀀스를 검색하고, 그 후 일치하는 정체성(데이터베이스 스키마와 시퀀스 이름 기반)을 가진 로컬 시퀀스를 갱신해요.
다음과 같이 명령을 사용할 수 있어요:
kubectl cnpg subscription sync-sequences \
--subscription SUBSCRIPTION_NAME \
LOCAL_CLUSTER
종합적인 세부 사항과 특정 지침은 다음 명령을 사용하세요:
kubectl cnpg subscription sync-sequences --help
예시 (Example)
publication과 subscription의 이전 섹션에서처럼, source-cluster와 destination-cluster가 있어요. 둘 다 app이라고 불리는 publication과 subscription이 이미 존재해요.
다음 명령은 app subscription에 관련된 시퀀스를 소스 클러스터에서 대상 클러스터로 동기화해요.
kubectl cnpg subscription sync-sequences destination-cluster \
--subscription=app
:::warning 프로덕션 환경에 배포하기 전에 비-프로덕션 환경에서 subscription 테스트를 우선해, 그 효과를 보장하고 잠재적 문제를 감지하세요. :::
K9s와의 통합 (Integration with K9s)
cnpg 플러그인은 Kubernetes 클러스터와 상호작용하는 인기 있는 터미널 기반 UI인 K9s에 쉽게 통합할 수 있어요.
세부 사항은 K9s repo를 참조하세요.
플러그인이 요구하는 권한 (Permissions required by the plugin)
플러그인은 실행할 명령에 따라 달라지는 일련의 Kubernetes 권한을 요구해요. 이 권한들은 Pods, PDBs, PVCs 같은 리소스와 하위 리소스에 영향을 주고 get, delete, patch 같은 작업을 가능하게 해요. 다음 표에 전체 세부 사항이 있어요:
| 명령 | 리소스 권한 |
|---|---|
| backup | clusters: get backups: create |
| certificate | clusters: get secrets: get,create |
| destroy | pods: get,delete jobs: delete,list PVCs: list,delete,update |
| fencing | clusters: get,patch pods: get |
| fio | PVCs: create configmaps: create deployment: create |
| hibernate | clusters: get,patch,delete pods: list,get,delete pods/exec: create jobs: list PVCs: get,list,update,patch,delete |
| install | 없음 |
| logs | clusters: get pods: list pods/log: get |
| maintenance | clusters: get,patch,list |
| pgadmin4 | clusters: get configmaps: create deployments: create services: create secrets: create |
| pgbench | clusters: get jobs: create |
| promote | clusters: get clusters/status: patch pods: get |
| psql | pods: get,list pods/exec: create |
| publication | clusters: get pods: get,list pods/exec: create |
| reload | clusters: get,patch |
| report cluster | clusters: get pods: list pods/log: get jobs: list events: list PVCs: list |
| report operator | 필수: deployments: get 선택 (전체 보고서용): configmaps: get events: list pods: list pods/log: get secrets: get services: get mutatingwebhookconfigurations: list[^1] validatingwebhookconfigurations: list[^1] OLM이 있으면: clusterserviceversions: list[^1] installplans: list[^1] subscriptions: list[^1] |
| restart | clusters: get,patch pods: get,delete |
| status | clusters: get pods: list pods/exec: create pods/proxy: create PDBs: list objectstores.barmancloud.cnpg.io: get |
| subscription | clusters: get pods: get,list pods/exec: create |
| version | 없음 |
[^1]: 권한은 클러스터 범위 ClusterRole 리소스입니다.
clusters에 list 권한을 할당하면 여러 명령의 자동 완성이 활성화돼요.
역할 예시 (Role examples)
제한된 권한을 가진 역할을 만드는 것이 가능해요. 다음 예시는 클러스터 로그에만 접근할 수 있는 역할을 만들어요:
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: cnpg-log
rules:
- verbs:
- get
apiGroups:
- postgresql.cnpg.io
resources:
- clusters
- verbs:
- list
apiGroups:
- ''
resources:
- pods
- verbs:
- get
apiGroups:
- ''
resources:
- pods/log
다음 예시는 플러그인의 status 명령으로 클러스터 상태를 얻는 데 필요한 최소 권한을 가진 역할을 보여줘요:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: cnpg-status
rules:
- verbs:
- get
apiGroups:
- postgresql.cnpg.io
resources:
- clusters
- verbs:
- list
apiGroups:
- ''
resources:
- pods
- verbs:
- create
apiGroups:
- ''
resources:
- pods/exec
- verbs:
- create
apiGroups:
- ''
resources:
- pods/proxy
- verbs:
- list
apiGroups:
- policy
resources:
- poddisruptionbudgets
- verbs:
- get
apiGroups:
- barmancloud.cnpg.io
resources:
- objectstores
:::info[Important]
resources별로 apiGroups별로 verbs를 제한된 상태로 유지하면 의도한 권한보다 더 많은 것을 실수로 부여하는 것을 방지하는 데 도움이 돼요.
:::