kmg28801 / kubernetes-study

2 stars 0 forks source link

Chapter 3. 파드 : 쿠버네티스에서 컨테이너 실행 #4

Open seojeonghyeon opened 2 years ago

seojeonghyeon commented 2 years ago

Chapter 3. 파드 : 쿠버네티스에서 컨테이너 실행

Main Point

1. Pod


Untitled

Pod는 Container Group이며, 기본 빌딩 블록(제품을 구성하는 각 구성 요소를 서로 독립된 모듈로 구성하는 방법)이다. 일반적으로 Pod는 하나의 컨테이너만 포함한다.

Pod가 필요한 이유

Muti Process Single Container VS Single Process Muti Container

Container는 단일 프로세스를 실행하는 것을 목적으로 설계되었다(프로세스가 자식 프로세스를 생성하는 것을 제외한다, 단일 프로세스를 제외한 다른 프로세스가 실행하게 될 때(프로세스 간 통신(IPC)을 위해, 또는 공유자원 이용 등) 프로세스 실행, 로그 관리 책임은 사용자에게 있다).

Untitled 1

Single Process Muti Container를 써야하는 이유

Container를 직접 이용하지 않고 Pod가 필요한 이유

Pod의 이해

같은 Pod에서 Container 간 부분 격리

그룹 안의 Container가 특정 Resource를 공유하기 위해 각 Container가 완벽하게 격리되지 않도록 한다. Kubernetes는 Pod 안에 있는 모든 Container가 동일한 리눅스 Namespace를 공유하도록 Docker를 설정한다.

Container가 동일한 IP와 포트 공간을 공유하는 방법

Pod 내 Container가 동일한 Network Namespace에서 실행되기 때문에, 동일한 IP 주소와 포트 공간을 공유한다.(동일 Pod 내 2개 이상의 프로세스가 같은 포트를 사용하면 충돌한다.) Pod 내 모든 Container는 동일한 Loopback Network Interface를 갖기 때문에 Conatiner들이 Localhost를 통해 서로 통신 가능하다.

Untitled 2

Pod 간 Flat Network

Pod는 논리적 Host로 Container가 아닌 환경에서의 물리적 Host와 매우 유사하게 동작한다.

Untitled 3

Pod 내 Container의 적절한 구성

Pod는 상대적으로 가볍기 때문에 오버헤드 없이 필요한 만큼 Pod를 가질 수 있다. Application을 여러 Pod로 구성하고 각 파드에는 밀접하게 관련 있는 구성 요소나 프로세스만 포함해야한다.

다계층 Application을 여러 Pod로 분할

프론트엔드와 백엔드가 같은 Pod 내에 존재하게 되면 두번째 노드에서 이용할 수 있는 컴퓨팅 리소스(CPU, Memory)를 활용하지 않고 버리게 된다. Pod를 두개로 분리하면 각기 다른 노드에 스케줄링해 Infra Structure의 활용도를 향상시킬 수 있다.

개별 확장이 가능하도록 여러 Pod로 분할

Pod는 Scaling의 기본 단위이다. Kubernetes는 개별 Container를 수평으로 확장할 수 없기 때문에 전체 Pod를 수평으로 확장한다. Container를 개별적으로 Scaling하는 것이 필요하다면, 별도의 Pod에 배포해야한다.

Pod에서 여러 Container를 사용하는 경우

Pod에 하나 이상의 Container가 들어가는 이유는 Main 프로세스와 Support 프로세스로 구성된 경우이다.(Support 프로세스 종류 : 외부 소스에서 주기적으로 콘텐츠를 받아 웹 서버의 디렉토리에 저장, 로그 로테이터, 로그 수집기, 데이터 프로세서, 통신 어댑터)

Pod에서 여러 Container를 사용해야하는 경우 고려사항

2. Pod 생성(YML or JSON 디스크립터)


kubectl run 명령으로 생성한 Pod는 제한된 속성 집합만 설정 가능하다. YML 파일에 Kubernetes Object를 정의하여 Pod를 생성하면 버전 관리가 가능하다. (Kubernetes API Reference Document)

YML 디스크립터

YML 디스크립터 예제



# 쿠버네티스 API 버전
apiVersion: v1

# 쿠버네티스 오브젝트/리소스 유형
kind: Pod

# 파드 메타데이터(이름, 레이블, 어노테이션 등)
metadata:
    annotations:
        kubernetes.io/created-by: Jeonghyeon Seo
    createionTimestamp: 2022-11-20T10:00:00Z
    generateName: kubia-
    labels:
        run: kubia
    name: kubia-zxzij
    namespace: default
    resourceVersion: "294"
    selfLink: /api/v1/namespaces/default/pods/kubia-zxzij
    uid: 3a564dc0-ed06-11e5-ba3b-42010af0004

# 파드 정의/내용 (파드 컨테이너 목록, 볼륨 등)
spec:
    containers:
    - image: luksa/kubia
        imagePullPolicy: IfNotPresent
        name: kubia
        ports:
        - containerPort: 8080
            protocol: TCP
        resources:
            requests:
                cpu: 100m
    terminationMessagePath: /dev/termination-log
    volumeMounts:
    - mountPath: /var/run/secrets/k8s.io/servacc
        name: default-token-kvcqa
        readOnly: true
    dnsPolicy: ClusterFirst
    nodeName: gke-kubia-e8fe08b8-node-txje
    restartPolicy: Always
    serviceAccount: default
    terminationGracePeriodSeconds: 30
    volumns:
    - name: default-token-kcvqa
        secret:
            secretName: default-token-kvcqa

# 파드와 그 안의 여러 컨테이너의 상세한 상태
    status:
        conditions:
        - lastProbeTime: null
            lastTransitionTime: null
            status: "True"
            type: Ready
    containerStatuses:
    - containerID: docker://f027...
    image: luksa/kubia
    imageID: docker://4c32..
    lastState: {}
    name: kubia
    ready: true
    restartCount: 0
    state:
        running:
        startedAt: 2022-11-20T09:00:00Z
hostIP: 10.132.0.4
phase: Running
podIP: 10.0.2.3
startTime: 2022-11-20T09:00:00Z

사용 가능한 API Object field 찾기(kubectl explain)


# Pod 속성
zayden@Zaydenui-MacBookPro  ~/Documents/Work/GoogleCloud  kubectl explain pod
s
W1119 13:03:39.618329    9884 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status   <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
# Pod Spec
zayden@Zaydenui-MacBookPro  ~/Documents/Work/GoogleCloud  kubectl explain p
od.spec
W1119 13:00:16.535618    9836 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
KIND:     Pod
VERSION:  v1

RESOURCE: spec <Object>

DESCRIPTION:
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

     PodSpec is a description of a pod.

FIELDS:
   activeDeadlineSeconds    <integer>
     Optional duration in seconds the pod may be active on the node relative to
     StartTime before the system will actively try to mark it failed and kill
     associated containers. Value must be a positive integer.

   affinity <Object>
     If specified, the pod's scheduling constraints

   automountServiceAccountToken <boolean>
     AutomountServiceAccountToken indicates whether a service account token
     should be automatically mounted.

   containers   <[]Object> -required-
     List of containers belonging to the pod. Containers cannot currently be
     added or removed. There must be at least one container in a Pod. Cannot be
     updated.

   dnsConfig    <Object>
     Specifies the DNS parameters of a pod. Parameters specified here will be
     merged to the generated DNS configuration based on DNSPolicy.

   dnsPolicy    <string>
     Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are
     'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS
     parameters given in DNSConfig will be merged with the policy selected with
     DNSPolicy. To have DNS options set along with hostNetwork, you have to
     specify DNS policy explicitly to 'ClusterFirstWithHostNet'.

   enableServiceLinks   <boolean>
     EnableServiceLinks indicates whether information about services should be
     injected into pod's environment variables, matching the syntax of Docker
     links. Optional: Defaults to true.

   ephemeralContainers  <[]Object>
     List of ephemeral containers run in this pod. Ephemeral containers may be
     run in an existing pod to perform user-initiated actions such as debugging.
     This list cannot be specified when creating a pod, and it cannot be
     modified by updating the pod spec. In order to add an ephemeral container
     to an existing pod, use the pod's ephemeralcontainers subresource. This
     field is beta-level and available on clusters that haven't disabled the
     EphemeralContainers feature gate.

   hostAliases  <[]Object>
     HostAliases is an optional list of hosts and IPs that will be injected into
     the pod's hosts file if specified. This is only valid for non-hostNetwork
     pods.

   hostIPC  <boolean>
     Use the host's ipc namespace. Optional: Default to false.

   hostNetwork  <boolean>
     Host networking requested for this pod. Use the host's network namespace.
     If this option is set, the ports that will be used must be specified.
     Default to false.

   hostPID  <boolean>
     Use the host's pid namespace. Optional: Default to false.

   hostname <string>
     Specifies the hostname of the Pod If not specified, the pod's hostname will
     be set to a system-defined value.

   imagePullSecrets <[]Object>
     ImagePullSecrets is an optional list of references to secrets in the same
     namespace to use for pulling any of the images used by this PodSpec. If
     specified, these secrets will be passed to individual puller
     implementations for them to use. For example, in the case of docker, only
     DockerConfig type secrets are honored. More info:
     https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod

   initContainers   <[]Object>
     List of initialization containers belonging to the pod. Init containers are
     executed in order prior to containers being started. If any init container
     fails, the pod is considered to have failed and is handled according to its
     restartPolicy. The name for an init container or normal container must be
     unique among all containers. Init containers may not have Lifecycle
     actions, Readiness probes, Liveness probes, or Startup probes. The
     resourceRequirements of an init container are taken into account during
     scheduling by finding the highest request/limit for each resource type, and
     then using the max of of that value or the sum of the normal containers.
     Limits are applied to init containers in a similar fashion. Init containers
     cannot currently be added or removed. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

   nodeName <string>
     NodeName is a request to schedule this pod onto a specific node. If it is
     non-empty, the scheduler simply schedules this pod onto that node, assuming
     that it fits resource requirements.

   nodeSelector <map[string]string>
     NodeSelector is a selector which must be true for the pod to fit on a node.
     Selector which must match a node's labels for the pod to be scheduled on
     that node. More info:
     https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

   os   <Object>
     Specifies the OS of the containers in the pod. Some pod and container
     fields are restricted if this is set.

     If the OS field is set to linux, the following fields must be unset:
     -securityContext.windowsOptions

     If the OS field is set to windows, following fields must be unset: -
     spec.hostPID - spec.hostIPC - spec.securityContext.seLinuxOptions -
     spec.securityContext.seccompProfile - spec.securityContext.fsGroup -
     spec.securityContext.fsGroupChangePolicy - spec.securityContext.sysctls -
     spec.shareProcessNamespace - spec.securityContext.runAsUser -
     spec.securityContext.runAsGroup - spec.securityContext.supplementalGroups -
     spec.containers[*].securityContext.seLinuxOptions -
     spec.containers[*].securityContext.seccompProfile -
     spec.containers[*].securityContext.capabilities -
     spec.containers[*].securityContext.readOnlyRootFilesystem -
     spec.containers[*].securityContext.privileged -
     spec.containers[*].securityContext.allowPrivilegeEscalation -
     spec.containers[*].securityContext.procMount -
     spec.containers[*].securityContext.runAsUser -
     spec.containers[*].securityContext.runAsGroup This is an alpha field and
     requires the IdentifyPodOS feature

   overhead <map[string]string>
     Overhead represents the resource overhead associated with running a pod for
     a given RuntimeClass. This field will be autopopulated at admission time by
     the RuntimeClass admission controller. If the RuntimeClass admission
     controller is enabled, overhead must not be set in Pod create requests. The
     RuntimeClass admission controller will reject Pod create requests which
     have the overhead already set. If RuntimeClass is configured and selected
     in the PodSpec, Overhead will be set to the value defined in the
     corresponding RuntimeClass, otherwise it will remain unset and treated as
     zero. More info:
     https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md
     This field is beta-level as of Kubernetes v1.18, and is only honored by
     servers that enable the PodOverhead feature.

   preemptionPolicy <string>
     PreemptionPolicy is the Policy for preempting pods with lower priority. One
     of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.
     This field is beta-level, gated by the NonPreemptingPriority feature-gate.

   priority <integer>
     The priority value. Various system components use this field to find the
     priority of the pod. When Priority Admission Controller is enabled, it
     prevents users from setting this field. The admission controller populates
     this field from PriorityClassName. The higher the value, the higher the
     priority.

   priorityClassName    <string>
     If specified, indicates the pod's priority. "system-node-critical" and
     "system-cluster-critical" are two special keywords which indicate the
     highest priorities with the former being the highest priority. Any other
     name must be defined by creating a PriorityClass object with that name. If
     not specified, the pod priority will be default or zero if there is no
     default.

   readinessGates   <[]Object>
     If specified, all readiness gates will be evaluated for pod readiness. A
     pod is ready when all its containers are ready AND all conditions specified
     in the readiness gates have status equal to "True" More info:
     https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates

   restartPolicy    <string>
     Restart policy for all containers within the pod. One of Always, OnFailure,
     Never. Default to Always. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy

   runtimeClassName <string>
     RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group,
     which should be used to run this pod. If no RuntimeClass resource matches
     the named class, the pod will not be run. If unset or empty, the "legacy"
     RuntimeClass will be used, which is an implicit class with an empty
     definition that uses the default runtime handler. More info:
     https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class This is a
     beta feature as of Kubernetes v1.14.

   schedulerName    <string>
     If specified, the pod will be dispatched by specified scheduler. If not
     specified, the pod will be dispatched by default scheduler.

   securityContext  <Object>
     SecurityContext holds pod-level security attributes and common container
     settings. Optional: Defaults to empty. See type description for default
     values of each field.

   serviceAccount   <string>
     DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
     Deprecated: Use serviceAccountName instead.

   serviceAccountName   <string>
     ServiceAccountName is the name of the ServiceAccount to use to run this
     pod. More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/

   setHostnameAsFQDN    <boolean>
     If true the pod's hostname will be configured as the pod's FQDN, rather
     than the leaf name (the default). In Linux containers, this means setting
     the FQDN in the hostname field of the kernel (the nodename field of struct
     utsname). In Windows containers, this means setting the registry value of
     hostname for the registry key
     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters to
     FQDN. If a pod does not have FQDN, this has no effect. Default to false.

   shareProcessNamespace    <boolean>
     Share a single process namespace between all of the containers in a pod.
     When this is set containers will be able to view and signal processes from
     other containers in the same pod, and the first process in each container
     will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
     be set. Optional: Default to false.

   subdomain    <string>
     If specified, the fully qualified Pod hostname will be
     "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
     specified, the pod will not have a domainname at all.

   terminationGracePeriodSeconds    <integer>
     Optional duration in seconds the pod needs to terminate gracefully. May be
     decreased in delete request. Value must be non-negative integer. The value
     zero indicates stop immediately via the kill signal (no opportunity to shut
     down). If this value is nil, the default grace period will be used instead.
     The grace period is the duration in seconds after the processes running in
     the pod are sent a termination signal and the time when the processes are
     forcibly halted with a kill signal. Set this value longer than the expected
     cleanup time for your process. Defaults to 30 seconds.

   tolerations  <[]Object>
     If specified, the pod's tolerations.

   topologySpreadConstraints    <[]Object>
     TopologySpreadConstraints describes how a group of pods ought to spread
     across topology domains. Scheduler will schedule pods in a way which abides
     by the constraints. All topologySpreadConstraints are ANDed.

   volumes  <[]Object>
     List of volumes that can be mounted by containers belonging to the pod.
     More info: https://kubernetes.io/docs/concepts/storage/volumes

YML파일로 nginx-pod-sample Pod 생성 및 확인


1. Script File

# nginx-sample.yml

# 쿠버네티스 API 버전
apiVersion: v1
# Object 종류 : Pod
kind: Pod

metadata:
    # Pod 이름
  name: nginx-pod-sample
spec:
  containers:
        # Container 이름
  - name: nginx
        # Container Image
    image: nginx:1.14.2
        #Application Port, Protocol
    ports:
    - containerPort : 80
      protocol: TCP

2. Script File 토대로 생성

# yml 파일을 토대로 생성
✘ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl create -f nginx-sample.yml
W1119 14:17:32.347999   10845 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
Warning: Autopilot set default resource requests for Pod default/nginx-pod-sample, as resource requests were not specified. See http://g.co/gke/autopilot-defaults.
pod/nginx-pod-sample created

3. Pod 전체 정의 확인

# YML파일로 Pod의 전체 정의 확인
✘ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po nginx-pod-sample -o yaml
W1119 14:20:17.660514   10902 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
apiVersion: v1
kind: Pod
metadata:
  annotations:
    autopilot.gke.io/resource-adjustment: '{"input":{"containers":[{"name":"nginx"}]},"output":{"containers":[{"limits":{"cpu":"500m","ephemeral-storage":"1Gi","memory":"2Gi"},"requests":{"cpu":"500m","ephemeral-storage":"1Gi","memory":"2Gi"},"name":"nginx"}]},"modified":true}'
    seccomp.security.alpha.kubernetes.io/pod: runtime/default
  creationTimestamp: "2022-11-19T05:17:33Z"
  name: nginx-pod-sample
  namespace: default
  resourceVersion: "77496"
  uid: 0ccc08ee-2387-4319-b1aa-f1958bfdfd37
spec:
  containers:
  - image: nginx:1.14.2
    imagePullPolicy: IfNotPresent
    name: nginx
    ports:
    - containerPort: 80
      protocol: TCP
    resources:
      limits:
        cpu: 500m
        ephemeral-storage: 1Gi
        memory: 2Gi
      requests:
        cpu: 500m
        ephemeral-storage: 1Gi
        memory: 2Gi
    securityContext:
      capabilities:
        drop:
        - NET_RAW
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-pprrl
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: gk3-autopilot-cluster-1-default-pool-ae4a96f4-4vfb
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: gke.io/optimize-utilization-scheduler
  securityContext:
    seccompProfile:
      type: RuntimeDefault
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  - effect: NoSchedule
    key: kubernetes.io/arch
    operator: Equal
    value: amd64
  volumes:
  - name: kube-api-access-pprrl
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:19:42Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:20:14Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:20:14Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:19:42Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: containerd://efc515c9f4175ec83b5760bdf1cb20b43f4fde468543a592a1d253eeb6afeaea
    image: docker.io/library/nginx:1.14.2
    imageID: docker.io/library/nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d
    lastState: {}
    name: nginx
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2022-11-19T05:20:13Z"
  hostIP: 10.160.0.6
  phase: Running
  podIP: 10.31.0.131
  podIPs:
  - ip: 10.31.0.131
  qosClass: Guaranteed
  startTime: "2022-11-19T05:19:42Z"
# JSON 파일로 Pod 전체 정의 확인
zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po nginx-pod-sample -o json
W1119 14:21:07.640471   10917 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "annotations": {
            "autopilot.gke.io/resource-adjustment": "{\"input\":{\"containers\":[{\"name\":\"nginx\"}]},\"output\":{\"containers\":[{\"limits\":{\"cpu\":\"500m\",\"ephemeral-storage\":\"1Gi\",\"memory\":\"2Gi\"},\"requests\":{\"cpu\":\"500m\",\"ephemeral-storage\":\"1Gi\",\"memory\":\"2Gi\"},\"name\":\"nginx\"}]},\"modified\":true}",
            "seccomp.security.alpha.kubernetes.io/pod": "runtime/default"
        },
        "creationTimestamp": "2022-11-19T05:17:33Z",
        "name": "nginx-pod-sample",
        "namespace": "default",
        "resourceVersion": "77496",
        "uid": "0ccc08ee-2387-4319-b1aa-f1958bfdfd37"
    },
    "spec": {
        "containers": [
            {
                "image": "nginx:1.14.2",
                "imagePullPolicy": "IfNotPresent",
                "name": "nginx",
                "ports": [
                    {
                        "containerPort": 80,
                        "protocol": "TCP"
                    }
                ],
                "resources": {
                    "limits": {
                        "cpu": "500m",
                        "ephemeral-storage": "1Gi",
                        "memory": "2Gi"
                    },
                    "requests": {
                        "cpu": "500m",
                        "ephemeral-storage": "1Gi",
                        "memory": "2Gi"
                    }
                },
                "securityContext": {
                    "capabilities": {
                        "drop": [
                            "NET_RAW"
                        ]
                    }
                },
                "terminationMessagePath": "/dev/termination-log",
                "terminationMessagePolicy": "File",
                "volumeMounts": [
                    {
                        "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
                        "name": "kube-api-access-pprrl",
                        "readOnly": true
                    }
                ]
            }
        ],
        "dnsPolicy": "ClusterFirst",
        "enableServiceLinks": true,
        "nodeName": "gk3-autopilot-cluster-1-default-pool-ae4a96f4-4vfb",
        "preemptionPolicy": "PreemptLowerPriority",
        "priority": 0,
        "restartPolicy": "Always",
        "schedulerName": "gke.io/optimize-utilization-scheduler",
        "securityContext": {
            "seccompProfile": {
                "type": "RuntimeDefault"
            }
        },
        "serviceAccount": "default",
        "serviceAccountName": "default",
        "terminationGracePeriodSeconds": 30,
        "tolerations": [
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/not-ready",
                "operator": "Exists",
                "tolerationSeconds": 300
            },
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/unreachable",
                "operator": "Exists",
                "tolerationSeconds": 300
            },
            {
                "effect": "NoSchedule",
                "key": "kubernetes.io/arch",
                "operator": "Equal",
                "value": "amd64"
            }
        ],
        "volumes": [
            {
                "name": "kube-api-access-pprrl",
                "projected": {
                    "defaultMode": 420,
                    "sources": [
                        {
                            "serviceAccountToken": {
                                "expirationSeconds": 3607,
                                "path": "token"
                            }
                        },
                        {
                            "configMap": {
                                "items": [
                                    {
                                        "key": "ca.crt",
                                        "path": "ca.crt"
                                    }
                                ],
                                "name": "kube-root-ca.crt"
                            }
                        },
                        {
                            "downwardAPI": {
                                "items": [
                                    {
                                        "fieldRef": {
                                            "apiVersion": "v1",
                                            "fieldPath": "metadata.namespace"
                                        },
                                        "path": "namespace"
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        ]
    },
    "status": {
        "conditions": [
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2022-11-19T05:19:42Z",
                "status": "True",
                "type": "Initialized"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2022-11-19T05:20:14Z",
                "status": "True",
                "type": "Ready"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2022-11-19T05:20:14Z",
                "status": "True",
                "type": "ContainersReady"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2022-11-19T05:19:42Z",
                "status": "True",
                "type": "PodScheduled"
            }
        ],
        "containerStatuses": [
            {
                "containerID": "containerd://efc515c9f4175ec83b5760bdf1cb20b43f4fde468543a592a1d253eeb6afeaea",
                "image": "docker.io/library/nginx:1.14.2",
                "imageID": "docker.io/library/nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
                "lastState": {},
                "name": "nginx",
                "ready": true,
                "restartCount": 0,
                "started": true,
                "state": {
                    "running": {
                        "startedAt": "2022-11-19T05:20:13Z"
                    }
                }
            }
        ],
        "hostIP": "10.160.0.6",
        "phase": "Running",
        "podIP": "10.31.0.131",
        "podIPs": [
            {
                "ip": "10.31.0.131"
            }
        ],
        "qosClass": "Guaranteed",
        "startTime": "2022-11-19T05:19:42Z"
    }
}

3. Pod 내 확인

# 생성된 Pod 확인
zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get pods
W1119 14:23:00.303366   10943 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME               READY   STATUS    RESTARTS   AGE
nginx-pod-sample   1/1     Running   0          5m27s
# log 확인, nginx log..나오는게 없다.
zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl logs nginx-pod-sample
W1119 14:24:08.964652   11014 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke

4. Pod 내 접근

zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl exec -it nginx-pod-sample -- /bin/bash
W1119 14:31:28.594640   11322 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
root@nginx-pod-sample:/# 

5. Local Port - Pod 연결

#Local PC의 Port와 Pod 연결

zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl port-forward nginx-pod-sample 8001:80
W1119 14:51:32.445505   11538 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
Forwarding from 127.0.0.1:8001 -> 80
Forwarding from [::1]:8001 -> 80
Handling connection for 8001
Handling connection for 8001
%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA_2022-11-19_14 54 00

Label로 파드를 구성

예) Label을 app(Application, 구성요소, Microservice)과 rel(stable, beta, canary)로 나누어, 2차원으로 구성

app=ui app=as app=pc app=sc app=os
rel=stable UI Pod Account Service Pod Product Catalog Pod Shopping Cart Pod Order Service Pod
rel=beta UI Pod Product Catalog Pod Order Service Pod
rel=canary Account Service Pod Product Catalog Pod Order Service Pod

Label을 지정하여 Pod 생성


1. Script File

# nginx-sample.yml

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod-sample-v2
    # Label 2개 추가
  labels:
    creation_method: sample
    env: stg
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort : 80
      protocol: TCP

2. Pod 생성 및 확인

# Pod 생성
✘ ⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl create -f nginx-sample.yml
W1119 15:21:02.975370   11955 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
Warning: Autopilot set default resource requests for Pod default/nginx-pod-sample-v2, as resource requests were not specified. See http://g.co/gke/autopilot-defaults.
pod/nginx-pod-sample-v2 created

# Label과 함께 Pod 나열
✘ ⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po --show-labels
W1119 15:21:45.145236   12026 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                  READY   STATUS    RESTARTS   AGE   LABELS
nginx-pod-sample      1/1     Running   0          64m   <none>
nginx-pod-sample-v2   0/1     Pending   0          39s   creation_method=sample,env=stg

# 일부 Label에 대해서만 부착한 상태에서 Pod 나열
✘ ⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po -L creation_method,env
W1119 15:22:41.966591   12051 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                  READY   STATUS    RESTARTS   AGE   CREATION_METHOD   ENV
nginx-pod-sample      1/1     Running   0          65m
nginx-pod-sample-v2   0/1     Pending   0          96s   sample            stg

3. Pod의 Label 수정 및 변경

# 수정 및 변경 전 Pod
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po -L creation_method,env
W1119 15:22:41.966591   12051 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                  READY   STATUS    RESTARTS   AGE   CREATION_METHOD   ENV
nginx-pod-sample      1/1     Running   0          65m
nginx-pod-sample-v2   0/1     Pending   0          96s   sample            stg

# Label을 추가
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl label po nginx-pod-sample creation_method=sample
W1119 15:28:00.508334   12110 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
pod/nginx-pod-sample labeled

# Label을 변경(Overwrite)
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl label po nginx-pod-sample-v2 env=prd --overwrite
W1119 15:29:18.224598   12128 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
pod/nginx-pod-sample-v2 labeled

# 수정 및 변경 후 Pod
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po -L creation_method,env
W1119 15:29:36.172046   12144 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                  READY   STATUS    RESTARTS   AGE     CREATION_METHOD   ENV
nginx-pod-sample      1/1     Running   0          72m     sample
nginx-pod-sample-v2   1/1     Running   0          8m30s   sample            prd

Label Selector

Label은 Label Selector와 함께 사용되는데, 특정 Label로 태크된 Pod의 부분 집합을 선택해 원하는 작업을 수행한다.

Label Selector가 Resource를 선택하는 기준

Label Selector로 Pod 조회


# creation_method가 sample인 모든 Pod 조회
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po -l creation_method=sample
W1119 15:39:59.343780   12257 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                  READY   STATUS    RESTARTS   AGE
nginx-pod-sample      1/1     Running   0          82m
nginx-pod-sample-v2   1/1     Running   0          18m
#env Label을 가진 Pod 하나 조회(아무거나)
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po -l env
W1119 15:42:42.851178   12292 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                  READY   STATUS    RESTARTS   AGE
nginx-pod-sample-v2   1/1     Running   0          21m
# Label 중 env가 없는  Pod 하나 조회(아무거나)
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po -l '!env'
W1119 15:43:11.338332   12305 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME               READY   STATUS    RESTARTS   AGE
nginx-pod-sample   1/1     Running   0          85m

Label과 Selector를 이용하여 Pod 스케줄링 제한

특정 Node에 Pod 스케줄링


1. 현재 Node 확인

⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get nodes
W1119 16:16:20.191488   12633 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME                                                 STATUS   ROLES    AGE     VERSION
gk3-autopilot-cluster-1-default-pool-6f5ec78c-1pqm   Ready    <none>   3h54m   v1.23.12-gke.100
gk3-autopilot-cluster-1-default-pool-6f5ec78c-zwxr   Ready    <none>   54m     v1.23.12-gke.100
gk3-autopilot-cluster-1-default-pool-ae4a96f4-4kdr   Ready    <none>   3h54m   v1.23.12-gke.100
gk3-autopilot-cluster-1-default-pool-ae4a96f4-4vfb   Ready    <none>   117m    v1.23.12-gke.100

2. 특정 Node에 Label 부여

#GKE에서 나만 안됨..? 노드풀로 구성되어 있어서 굳이 필요없는 기능이라는 건가..

#하나의 노드에 ssd=true Label 부여
kubectl label node gk3-autopilot-cluster-1-default-node-4vfb ssd=true

# ssd=true Label 확인
kubectl get nodes -1 ssd=true

3. 특정 Label을 가진 Node에 생성

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod-sample-v2
  labels:
    creation_method: sample
    env: stg
spec:
  nodeSelector:
    sdd: "true"
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort : 80
      protocol: TCP

Annotations

Pod 안에서 Annotation 확인, 추가


1. Annotation 확인

# YML파일로 Pod의 전체 정의 확인
✘ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get po nginx-pod-sample -o yaml
W1119 14:20:17.660514   10902 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
apiVersion: v1
kind: Pod
metadata:
    **#Annotations 부분
  annotations:
    autopilot.gke.io/resource-adjustment: '{"input":{"containers":[{"name":"nginx"}]},"output":{"containers":[{"limits":{"cpu":"500m","ephemeral-storage":"1Gi","memory":"2Gi"},"requests":{"cpu":"500m","ephemeral-storage":"1Gi","memory":"2Gi"},"name":"nginx"}]},"modified":true}'
    seccomp.security.alpha.kubernetes.io/pod: runtime/default**
  creationTimestamp: "2022-11-19T05:17:33Z"
  name: nginx-pod-sample
  namespace: default
  resourceVersion: "77496"
  uid: 0ccc08ee-2387-4319-b1aa-f1958bfdfd37
spec:
  containers:
  - image: nginx:1.14.2
    imagePullPolicy: IfNotPresent
    name: nginx
    ports:
    - containerPort: 80
      protocol: TCP
    resources:
      limits:
        cpu: 500m
        ephemeral-storage: 1Gi
        memory: 2Gi
      requests:
        cpu: 500m
        ephemeral-storage: 1Gi
        memory: 2Gi
    securityContext:
      capabilities:
        drop:
        - NET_RAW
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-pprrl
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: gk3-autopilot-cluster-1-default-pool-ae4a96f4-4vfb
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: gke.io/optimize-utilization-scheduler
  securityContext:
    seccompProfile:
      type: RuntimeDefault
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  - effect: NoSchedule
    key: kubernetes.io/arch
    operator: Equal
    value: amd64
  volumes:
  - name: kube-api-access-pprrl
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:19:42Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:20:14Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:20:14Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2022-11-19T05:19:42Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: containerd://efc515c9f4175ec83b5760bdf1cb20b43f4fde468543a592a1d253eeb6afeaea
    image: docker.io/library/nginx:1.14.2
    imageID: docker.io/library/nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d
    lastState: {}
    name: nginx
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2022-11-19T05:20:13Z"
  hostIP: 10.160.0.6
  phase: Running
  podIP: 10.31.0.131
  podIPs:
  - ip: 10.31.0.131
  qosClass: Guaranteed
  startTime: "2022-11-19T05:19:42Z"

2. Annotation 추가

⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl annotate pod nginx-pod-sample hyundai-autoever.com/someannotation="foo
bar"
W1119 17:04:15.483544   13288 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
pod/nginx-pod-sample annotated
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl describe pod nginx-pod-sample
W1119 17:06:08.825275   13315 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
Name:             nginx-pod-sample
Namespace:        default
Priority:         0
Service Account:  default
Node:             gk3-autopilot-cluster-1-default-pool-ae4a96f4-4vfb/10.160.0.6
Start Time:       Sat, 19 Nov 2022 14:19:42 +0900
Labels:           creation_method=sample
**Annotations:      autopilot.gke.io/resource-adjustment:
                    {"input":{"containers":[{"name":"nginx"}]},"output":{"containers":[{"limits":{"cpu":"500m","ephemeral-storage":"1Gi","memory":"2Gi"},"requ...
                  hyundai-autoever.com/someannotation: foo bar
                  seccomp.security.alpha.kubernetes.io/pod: runtime/default**
Status:           Running
IP:               10.31.0.131
IPs:
  IP:  10.31.0.131
Containers:
  nginx:
    Container ID:   containerd://efc515c9f4175ec83b5760bdf1cb20b43f4fde468543a592a1d253eeb6afeaea
    Image:          nginx:1.14.2
    Image ID:       docker.io/library/nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sat, 19 Nov 2022 14:20:13 +0900
    Ready:          True
    Restart Count:  0
    Limits:
      cpu:                500m
      ephemeral-storage:  1Gi
      memory:             2Gi
    Requests:
      cpu:                500m
      ephemeral-storage:  1Gi
      memory:             2Gi
    Environment:          <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-pprrl (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-pprrl:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Guaranteed
Node-Selectors:              <none>
Tolerations:                 kubernetes.io/arch=amd64:NoSchedule
                             node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:                      <none>

Namespace 그룹화

Namespace 확인 및 생성


1. Namespace 확인

⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get ns
W1119 17:28:32.434476   13553 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME              STATUS   AGE
default           Active   5h8m
kube-node-lease   Active   5h8m
kube-public       Active   5h8m

2. Namespace 생성

# custom-namespace.yml
apiVersion: v1
kind: Namespace
metadata:
    name: custom-namespace
# Shell 명령
kubectl create namespace custome-namespace
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get ns
W1119 17:28:32.434476   13553 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME              STATUS   AGE
default           Active   5h8m
kube-node-lease   Active   5h8m
kube-public       Active   5h8m
kube-system       Active   5h8m
 ⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl create -f custom-namespace.yml
W1119 17:34:24.555907   13625 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
namespace/custom-namespace created
 ⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl get ns
W1119 17:34:32.882826   13670 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
NAME               STATUS   AGE
custom-namespace   Active   6s
default            Active   5h14m
kube-node-lease    Active   5h14m
kube-public        Active   5h14m
kube-system        Active   5h14m
# yml파일을 통해 명령 시, namespace 할당
kubectl create -f ngnix-pod-sample.yml -n custom-namespace

3. Pod 중지와 제거


Kubernetes는 Pod 안에 있는 모든 Container를 종료하도록 지시한다. Kubernetes는 SIGTERM 신호를 프로세스에 보내고 지정된 시간(Default:30초) 동안 기다린다. 시간내에 종료되지 않으면 SIGKILL 신호를 통해 종료한다. 프로세스가 정상적으로 종료되게 하기 위해 SIGTERM신호를 올바르게 처리해야 한다.

Pod 삭제


1. 이름으로 삭제

⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl delete po nginx-pod-sample
W1119 17:47:40.371340   13812 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
pod "nginx-pod-sample" deleted

2. Label Selector로 삭제

⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl delete po -l creation_method=sample
W1119 17:51:48.109836   13868 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
pod "nginx-pod-sample-v2" deleted

3. Namespace로 삭제

# Namespace에 해당되어 있는 Pod는 Namespace와 자동으로 삭제
⚙ zayden@Zaydenui-MacBookPro  ~/Documents/Work/kubernetes-repo  kubectl delete ns custom-namespace
W1119 17:52:40.536235   13883 gcp.go:119] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.26+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
namespace "custom-namespace" deleted

4. Namespace 내 모든 Pod 삭제

kubectl delete po --all

5. Namespace 내 거의 모든 리소스 삭제

# 특정 리소스는 보존된다.(7장 자세히)
kubectl delete all --all
seojeonghyeon commented 2 years ago

Notion Link : https://seojeonghyeon0630.notion.site/Chapter-3-cc541068313c4371806551474f06c02c

seojeonghyeon commented 2 years ago

끝!

kmg28801 commented 2 years ago

@seojeonghyeon 고생하셨습니다.