본문 바로가기
CKA

[CKAD] 연습문제 정리 4탄!

by 싱숭생숭늉 2024. 8. 21.

 

 

해당 연습문제는 이성미강사님의 강의를 바탕으로 작성했다.

 

https://fastcampus.co.kr/dev_online_kubemaster

 

정말 좋은 강의이다! 기초부터 탄탄하게 알고 싶다면 보는 것을 적극 추천한다!!

https://www.youtube.com/watch?v=6n5obRKsCRQ&list=PLApuRlvrZKohaBHvXAOhUD-RxD0uQ3z0c

 

 

문제를 풀때 https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands

해당 경로를 많이 사용하고 많이 참고 했다.

 

시험 시간이 넉넉하지는 않았다 그래서 타이핑 시간과 삭제시간(pod 잘 못 생성시 삭제가 필요)을 줄이기 위해 아래 명령어를 사용했다. (https://peterica.tistory.com/540 피터님이 알려주신 좋은 꿀팁!)

# "kubectl"를 "k"약자로 변경
alias k=kubectl
# yaml파일과 문법이 정상적으로 작동하는 지 확인
export do="--dry-run=client -o yaml" # k create deploy nginx --image=nginx $do
# pod삭제 시 바로 삭제
export now="--force --grace=period 0" # k delete pod nginx $now

 

1. Secret

Context:

  • You are tasked to create a secret and consume the secret in a pod using environment variables as follow:

Task:

  • Create a secret named another-secret with a key/value pair: key1/value3
  • Start an nginx pod named nginx-secret using container image nginx, and add an environment variable exposing the value of the secret key key1, using FC_VARIABLE as the name for the environment variable inside the pod
k create secret generic another-secret --from-literal=key1=value3
k run nginx-secret --image=nginx --dry-run=client -o yaml > nginx-secret.yaml

 

참고 : https://kubernetes.io/docs/tasks/inject-data-application/distribute-credentials-secure/#define-container-environment-variables-using-secret-data

apiVersion: v1
kind: Pod
metadata:
  name: nginx-secret
spec:
  containers:
  - name: nginx-secret
    image: nginx
    env:
    - name: FC_VARIABLE
      valueFrom:
        secretKeyRef:
          name: another-secret
          key: key1

 

2. Pod Resource

Task:

  • You are required to create a pod that requests a certain amount of CPU and memory, so it gets scheduled to a node that has those resources available.
    • Create a pod named nginx-resources in the presales namespace that requests a minimum of 200m CPU and 500Mi memory for its container.
    • The pod should use the nginx image. The presales namespace has already been created.
k create ns presales
k run nginx-resources --image=nginx -n presales --dry-run=client -o yaml > nginx-resources.yaml

 

참고 : https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#example-1

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx-resources
  name: nginx-resources
  namespace: presales
spec:
  containers:
  - image: nginx
    name: nginx-resources
    resources:  # 추가 된 내용
      requests:
        memory: "500Mi"
        cpu: "200m" 
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

3. ConfigMap

Context:

  • You are tasked to create a ConfigMap and consume the ConfigMap in a pod using a volume mount.

Task:

  • Please complete the following:
    • Create a ConfigMap named app-config containing the key/value pair: key2/value4
    • Start a pod named nginx-configmap containing a single container using the nginx image, and mount the key you just created into the pod under directory /app/data
k create cm app-config --from-literal=key2=value4
k run nginx-configmap --image=nginx --dry-run=client -o yaml > nginx-configmap.yaml

 

참고 : https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#add-configmap-data-to-a-volume

참고 : https://kubernetes.io/docs/concepts/storage/volumes/#configmap

 

apiVersion: v1
kind: Pod
metadata:
  name: nginx-configmap
spec:
  containers:
  - name: nginx-configmap
    image: nginx
    volumeMounts:  # 추가 된 부분
    - name: app-config  # 임의의 값 입력
      mountPath: "/app/data"  # 데이터가 저장되어야 하는 위치 설정
  volumes:
  - name: app-config  # 위의 값과 동일
    configMap:
      name: app-config  # 생성한 config name 사용

 

4. LivenessProbes and ReadinessProbes

Context:

  • A pod is running on the cluster but it is not responding.

Task:

  • The desired behavior is to have Kubernetes restart the pod when an endpoint returns an HTTP 500 on the /healthz endpoint.
  • The service probe-pod should never send traffic to the pod while it is failing.
  • Please complete the following:
    • The application has another endpoint /healthz that will indicate if the application is still working as expected by returning an HTTP 200. If the endpoint returns an HTTP 500 the application is no longer responsive.
    • The application has an endpoint, /started, that will indicate if it can accept traffic by returning an HTTP 200. If the endpoint returns an HTTP 500, the application has not yet finished initialization.
    • Configure the probe-pod pod provided to use these endpoints.
    • The probes should use port 80.

 

k run probe-pod --image=smlinux/web:probe --dry-run=client -o yaml > probe-pod.yaml

 

container port 부분 추가

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: probe-pod
  name: probe-pod
  namespace: default
spec:
  containers:
  - image: smlinux/web:probe
    imagePullPolicy: IfNotPresent
    name: probe-pod
    ports:  # 추가 된 부분
    - containerPort: 80
      protocol: TCP

 

서비스를 배포해 준다.

k expose pod probe-pod --port=80 --tyep=NodePort

 

 

  • Liveness Probe: 이 프로브는 애플리케이션이 여전히 실행 중인지 확인합니다. 만약 애플리케이션이 더 이상 응답하지 않으면, Kubernetes는 해당 컨테이너를 재시작합니다.
  • Readiness Probe: 이 프로브는 애플리케이션이 트래픽을 받을 준비가 되었는지를 확인합니다. 만약 애플리케이션이 준비되지 않은 상태라면, Kubernetes는 서비스가 해당 Pod으로 트래픽을 보내지 않도록 합니다.

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: probe-pod
  name: probe-pod
spec:
  containers:
  - image: smlinux/web:probe
    name: probe-pod
    ports:
    - containerPort: 80
      protocol: TCP
    livenessProbe:  # 추가 된 부분
      httpGet:
        path: /healthz
        port: 80
    readinessProbe:  # 추가 된 부분
      httpGet:
        path: /started
        port: 80

 

5. service account to be used

kubectl config use context k8s

Context:

  • Your application's namespace requires a specific service account to be used.

Task:

  • Update the app-deploy deployment in the production namespace to run as the app-ac service account.
  • The service account has already been created.
k create ns production
k create deploy app-deploy --image=nginx --replicas=2 -n production --dry-run=client -o yaml > app-deploy.yaml
k create sa app-ac -n production

 

k get deploy -n production app-deploy -o yaml | grep -i serviceaccount

기본 계정으로 설정이 되어있음

 

참고 : https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#opt-out-of-api-credential-automounting

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: app-deploy
  name: app-deploy
  namespace: production
spec:
  replicas: 2
  selector:
    matchLabels:
      app: app-deploy
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: app-deploy
    spec:
      containers:
      - image: nginx
        imagePullPolicy: Always
        name: nginx
      serviceAccountName: app-ac  # 추가 된 부분

 

자원 삭제 후 재배포

 

추가적으로 CLI를 사용해 serviceaccount 설정 가능

kubectl set serviceaccount deployment/app-deploy app-ac -n production

 

6. CronJob

Task:

  • Create a Pod starting at a predetermined time and running to completion only once each time it starts.
    • Define the Pod in the manifest file /data/ckad/ckad-cron.yaml. It must run the command uname in a single busybox:stable container. The command must run every minute and must complete within 10 seconds or be terminated by Kubernetes.
    • The CronJob name and container name must both be ckad.
    • Create the resource in the above manifest and verify that the job executes successfully at least once.
    • Ensure to use the busybox:stable, and not the busybox:lastest Image. Using the wrong image may lead to hitting a Docker hub rate limit negatively affecting your exam experience and scoring of this and other tasks.

참고 : https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/

yaml 파일을 /data/ckad/ckad-cron.yaml 저장

apiVersion: batch/v1
kind: CronJob
metadata:
  name: ckad
spec:
  schedule: "* * * * *"  # 매 분 마다 실행
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: ckad
            image: busybox:stable  # lastest 사용시 시험에 불이익!
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - uname; sleep 10  # uname 명령어 실행하고, 10초 잠궈라!
          restartPolicy: OnFailure

 

cronjob을 작업 후, 최소한 한 번 이상 성공적으로 실행되었는지 확인!

k get cronjob
k get pod --watch

 

 

7. Declare a LimitRange within a Namespace

Context:

  • Declare a LimitRange within a Namespace to create default resources.requests and resources.limits for all Pods created within that Namespace.

Task:

  • Create a LimitRange named app-limit-range with the following conditions:
    • If a Container is created in the devops namespace without specifying its own request or limits then default memory request is created for that Container of 256 Mibibytes and a memory limit of 512 Mibibytes.

참고 : https://kubernetes.io/docs/concepts/policy/limit-range/#constraints-on-resource-limits-and-requests

 

apiVersion: v1
kind: LimitRange
metadata:
  name: app-limit-range  # name 설정
  namespace: devops  # 적용할 namespace 설정
spec:
  limits:
  - default:  # 기본 메모리 제한 (제한이 설정되지 않은 컨테이너에 대한 기본 메모리 요청)
      memory: 512Mi
    defaultRequest:  # 기본 메모리 요청 (요청이 설정되지 않은 컨테이너에 대한 기본 메모리 요청)
      memory: 256Mi
    type: Container

 

'CKA' 카테고리의 다른 글

[CKAD] 연습문제 정리 5탄!!  (0) 2024.08.22
[CKA] 연습문제 정리 3탄!  (0) 2024.08.14
[CKA] 연습문제 정리 2탄!  (0) 2024.08.08
[CKA] 연습문제 정리 1탄!  (0) 2024.08.07
[CKA] 자격증 준비  (0) 2024.08.07