Kubernetes Expose 명령어

KubernetesBeginner
지금 연습하기

소개

Kubernetes 의 expose 명령어는 파드 (pod) 또는 디플로이먼트 (deployment) 를 네트워크 서비스를 통해 접근 가능하게 만드는 간단하면서도 강력한 도구입니다. 이 랩에서는 Kubernetes 클러스터를 시작하고, 디플로이먼트를 생성하며, 이를 서비스로 노출하고, 서비스에 접근하여 기능을 확인하는 과정을 안내합니다. 이 랩을 완료하면 Kubernetes 에서 디플로이먼트를 노출하고 서비스로 작업하는 방법에 대한 명확한 이해를 얻게 될 것입니다.

이것은 가이드 실험입니다. 학습과 실습을 돕기 위한 단계별 지침을 제공합니다.각 단계를 완료하고 실무 경험을 쌓기 위해 지침을 주의 깊게 따르세요. 과거 데이터에 따르면, 이것은 초급 레벨의 실험이며 완료율은 97%입니다.학습자들로부터 100%의 긍정적인 리뷰율을 받았습니다.

Minikube 시작

Kubernetes 를 로컬에서 실행하기 위해, 단일 노드 Kubernetes 클러스터를 설정하는 Minikube 를 사용합니다. Kubernetes 작업을 진행하기 전에 Minikube 가 실행 중인지 확인하십시오.

  1. 터미널을 열고 다음 명령으로 Minikube 를 시작합니다.

    minikube start

    이 명령은 클러스터를 초기화합니다. 필요한 경우, --cpus--memory와 같은 플래그를 사용하여 리소스 제한을 지정하여 클러스터에 충분한 리소스를 할당할 수 있습니다.

  2. Minikube 가 실행 중인지 확인합니다.

    minikube status

    클러스터와 해당 구성 요소가 성공적으로 실행 중임을 확인할 수 있습니다.

Minikube 를 시작하면 Kubernetes 가 후속 단계에서 디플로이먼트 (deployment) 및 서비스를 관리할 준비가 됩니다.

Deployment 생성

Kubernetes 에서 디플로이먼트는 애플리케이션이 항상 원하는 수의 레플리카 (replica) 를 실행하도록 보장하는 리소스 객체입니다. 디플로이먼트는 파드 (pod) 를 관리하고 클러스터 내에서 해당 상태를 유지하는 데 도움을 줍니다. 이 단계에서는 Nginx 웹 서버를 실행하는 디플로이먼트를 생성합니다.

  1. 다음 명령을 사용하여 nginx 이미지를 사용하는 hello-world라는 이름의 디플로이먼트를 생성합니다.

    kubectl create deployment hello-world --image=nginx

    이 명령은 Nginx 웹 서버를 실행하는 단일 파드를 가진 디플로이먼트를 생성합니다. --image 플래그는 사용할 컨테이너 이미지를 지정합니다. 레플리카가 명시적으로 설정되지 않았으므로 Kubernetes 는 기본적으로 하나의 파드를 생성합니다.

  2. 디플로이먼트가 성공적으로 생성되었는지 확인하려면 다음을 실행합니다.

    kubectl get deployments

    이 명령은 현재 네임스페이스의 모든 디플로이먼트를 나열하여 이름, 원하는 레플리카 수 및 상태를 표시합니다.

이 디플로이먼트를 생성함으로써 Kubernetes 가 원하는 애플리케이션 상태를 유지하기 위해 파드 생성 및 재시작을 자동으로 처리하도록 보장합니다.

kubectl expose 명령어 탐색

kubectl expose 명령어는 파드 (pod), 디플로이먼트 (deployment), 또는 레플리케이션 컨트롤러 (replication controller) 와 같은 기존 리소스를 노출하기 위해 새로운 Kubernetes 서비스를 생성하는 데 사용됩니다. 이 명령어는 제공된 리소스를 기반으로 서비스를 자동으로 생성하여 네트워킹 구성을 단순화합니다.

kubectl expose에 사용 가능한 옵션을 보려면 다음 명령을 실행하십시오.

kubectl expose -h

다음과 같은 출력을 볼 수 있습니다.

Expose a resource as a new Kubernetes service.

Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector for that
resource as the selector for a new service on the specified port. A deployment or replica set will be exposed as a
service only if its selector is convertible to a selector that service supports, i.e. when the selector contains only
the matchLabels component. Note that if no port is specified via --port and the exposed resource has multiple ports, all
will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the
resource it exposes.

Possible resources include (case insensitive):
  pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)

Examples:
  ## Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000
  kubectl expose rc nginx --port=80 --target-port=8000

  ## Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml",
  which serves on port 80 and connects to the containers on port 8000
  kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000

  ## Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
  kubectl expose pod valid-pod --port=444 --name=frontend

  ## Create a second service based on the above service, exposing the container port 8443 as port 443 with the name
  "nginx-https"
  kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https

  ## Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.
  kubectl expose rc streamer --port=4100 --protocol=UDP --name=video-stream

  ## Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on
  port 8000
  kubectl expose rs nginx --port=80 --target-port=8000

  ## Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000
  kubectl expose deployment nginx --port=80 --target-port=8000

Deployment 노출 (Expose)

Kubernetes 클러스터 외부에서 디플로이먼트에 접근할 수 있도록 하려면 이를 서비스 (service) 로 노출해야 합니다. Kubernetes 의 서비스는 기본 파드 (pod) 가 변경되더라도 안정적인 네트워크 엔드포인트 역할을 합니다.

  1. 다음 명령을 실행하여 hello-service라는 이름의 NodePort 서비스를 생성합니다.

    kubectl expose deployment hello-world --name=hello-service --port=80 --target-port=80 --type=NodePort
    • --port 플래그는 서비스가 외부 클라이언트에 노출할 포트를 지정합니다.
    • --target-port 플래그는 서비스가 트래픽을 라우팅할 컨테이너의 포트를 정의합니다.
    • --type=NodePort 플래그는 클러스터의 각 노드에서 특정 포트를 통해 서비스에 접근할 수 있도록 합니다.
  2. 서비스가 성공적으로 생성되었는지 확인합니다.

    kubectl get services hello-service

    이 명령은 서비스의 유형과 할당된 NodePort 를 포함한 서비스의 세부 정보를 표시합니다.

NodePort 와 같은 서비스는 외부 클라이언트가 올바른 컨테이너 포트로 요청을 전달하여 Kubernetes 클러스터의 파드와 상호 작용할 수 있도록 합니다.

Service 상세 정보 확인

노출된 서비스에 접근하려면 서비스에 할당된 NodePort 와 클러스터 내 노드의 내부 IP 주소가 필요합니다. 이러한 세부 정보는 외부 클라이언트가 애플리케이션에 연결할 수 있도록 합니다.

  1. 다음 명령을 실행하여 hello-service에 할당된 NodePort 를 검색합니다.

    kubectl get service hello-service -o jsonpath='{.spec.ports[0].nodePort}'

    이 명령은 서비스 정의에서 NodePort 값을 추출합니다.

  2. 다음 명령을 사용하여 클러스터 내 모든 노드의 내부 IP 주소를 얻습니다.

    kubectl get nodes -o wide

    출력에서 INTERNAL-IP 필드를 확인하십시오. 이 IP 주소는 노드의 개인 네트워크 주소를 나타냅니다.

NodePort 와 InternalIP 를 사용하면 이제 외부에서 서비스에 접근하는 데 필요한 세부 정보를 갖게 됩니다.

Service 접속 확인

NodePort 와 노드의 IP 주소를 사용하여 curl 또는 웹 브라우저와 같은 도구를 사용하여 서비스를 테스트할 수 있습니다.

  1. 이전 단계에서 검색한 값으로 <NODE_IP><NODE_PORT>를 대체한 다음 실행합니다.

    curl <NODE_IP>:<NODE_PORT>
  2. 모든 것이 올바르게 구성되어 있으면 터미널에서 기본 Nginx 환영 페이지를 볼 수 있습니다. 이 출력은 서비스가 실행 중이며 외부에서 접근할 수 있음을 확인합니다.

<!doctype html>
<html>
  <head>
    <title>Welcome to nginx!</title>
    <style>
      html {
        color-scheme: light dark;
      }
      body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Welcome to nginx!</h1>
    <p>
      If you see this page, the nginx web server is successfully installed and
      working. Further configuration is required.
    </p>

    <p>
      For online documentation and support please refer to
      <a href="http://nginx.org/">nginx.org</a>.<br />
      Commercial support is available at
      <a href="http://nginx.com/">nginx.com</a>.
    </p>

    <p><em>Thank you for using nginx.</em></p>
  </body>
</html>

서비스에 접근하는 것은 Kubernetes 가 클라이언트와 적절한 컨테이너 포트 간의 트래픽 라우팅을 처리하는 방식을 보여줍니다.

리소스 정리

실습을 완료한 후에는 Kubernetes 클러스터에서 불필요한 리소스 소비를 방지하기 위해 생성한 리소스를 정리하는 것이 중요합니다.

  1. 다음 명령을 실행하여 hello-service를 삭제합니다.

    kubectl delete service hello-service
  2. 다음 명령으로 hello-world 배포를 제거합니다.

    kubectl delete deployment hello-world

리소스를 정리하면 클러스터가 향후 실험을 위해 깨끗한 상태로 유지됩니다.

요약

이 실습에서는 Kubernetes 에서 expose 명령을 사용하여 NodePort 서비스를 생성하는 방법을 배웠습니다. Nginx 배포를 노출하고 NodePort 를 통해 액세스하여 기능을 확인했습니다. 이 연습은 Kubernetes 서비스의 핵심 개념과 서비스가 워크로드에 네트워크 접근을 제공하는 방법을 보여주었습니다.