본문 바로가기

리눅스

[kubernetes] kubectl run 명령

728x90

kubectl run 명령

Create and run a particular image in a pod.

사용법

Examples:
  # Start a nginx pod
  kubectl run nginx --image=nginx

  # Start a hazelcast pod and let the container expose port 5701
  kubectl run hazelcast --image=hazelcast/hazelcast --port=5701

  # Start a hazelcast pod and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the
container
  kubectl run hazelcast --image=hazelcast/hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"

  # Start a hazelcast pod and set labels "app=hazelcast" and "env=prod" in the container
  kubectl run hazelcast --image=hazelcast/hazelcast --labels="app=hazelcast,env=prod"

  # Dry run; print the corresponding API objects without creating them
  kubectl run nginx --image=nginx --dry-run=client

  # Start a nginx pod, but overload the spec with a partial set of values parsed from JSON
  kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'

  # Start a busybox pod and keep it in the foreground, don't restart it if it exits
  kubectl run -i -t busybox --image=busybox --restart=Never

  # Start the nginx pod using the default command, but use custom arguments (arg1 .. argN) for that command
  kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>

  # Start the nginx pod using a different command and custom arguments
  kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --annotations=[]: Annotations to apply to the pod.
      --attach=false: If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...'
were called.  Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the
exit code of the container process is returned.
      --cascade='background': Must be "background", "orphan", or "foreground". Selects the deletion cascading strategy
for the dependents (e.g. Pods created by a ReplicationController). Defaults to background.
      --command=false: If true and extra arguments are present, use them as the 'command' field in the container, rather
than the 'args' field which is the default.
      --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be
sent, without sending it. If server strategy, submit server-side request without persisting the resource.
      --env=[]: Environment variables to set in the container.
      --expose=false: If true, service is created for the container(s) which are run
      --field-manager='kubectl-run': Name of the manager used to track field ownership.
  -f, --filename=[]: to use to replace the resource.
      --force=false: If true, immediately remove resources from API and bypass graceful deletion. Note that immediate
deletion of some resources may result in inconsistency or data loss and requires confirmation.
      --grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.
Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
      --image='': The image for the container to run.
      --image-pull-policy='': The image pull policy for the container. If left empty, this value will not be specified
by the client and defaulted by the server
  -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R.
  -l, --labels='': Comma separated labels to apply to the pod(s). Will override previous values.
      --leave-stdin-open=false: If the pod is started in interactive mode or with stdin, leave stdin open after the
first attach completes. By default, stdin will be closed after the first attach completes.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file.
      --overrides='': An inline JSON override for the generated object. If this is non-empty, it is used to override the
generated object. Requires that the object supply a valid apiVersion field.
      --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running
      --port='': The port that this container exposes.
      --privileged=false: If true, run the container in privileged mode.
  -q, --quiet=false: If true, suppress prompt messages.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --restart='Always': The restart policy for this Pod.  Legal values [Always, OnFailure, Never].
      --rm=false: If true, delete resources created in this command for attached containers.
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --show-managed-fields=false: If true, keep the managedFields when printing objects in JSON or YAML format.
  -i, --stdin=false: Keep stdin open on the container(s) in the pod, even if nothing is attached.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --timeout=0s: The length of time to wait before giving up on a delete, zero means determine a timeout from the
size of the object
  -t, --tty=false: Allocated a TTY for each container in the pod.
      --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.

Usage:
  kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client] [--overrides=inline-json]
[--command] -- [COMMAND] [args...] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

트레이드 오프(Trade-offs)

kubectl 도구는 세 가지 종류의 객체 관리를 지원합니다.

- 명령형 커맨드(Imperative commands)

- 명령형 오브젝트 구성(Imperative object configuration)

- 선언형 오브젝트 구성(Declarative object configuration)

각 개체 관리 유형의 장단점에 대한 설명은 Kubernetes 개체 관리를 참조하세요

 

명령형 커맨드(Imperative commands)

kubectl run 명령

kubectl run nginx --image nginx
$ kubectl run nginx --image nginx
pod/nginx created
$ kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          50s

kubectl describe 명령

kubectl describe pods nginx
$ kubectl describe pods nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         kube-node2/192.168.56.22
Start Time:   Sat, 01 Oct 2022 16:54:10 +0900
Labels:       run=nginx
Annotations:  cni.projectcalico.org/containerID: af88356aaf248f17396f20f1dda6c6b912773f493105ff456d5f953af3f6a79c
              cni.projectcalico.org/podIP: 10.233.74.2/32
              cni.projectcalico.org/podIPs: 10.233.74.2/32
Status:       Running
IP:           10.233.74.2
IPs:
  IP:  10.233.74.2
Containers:
  nginx:
    Container ID:   docker://1a58344645845c0f16e99977d808a57e0ecebf337b9f7d080b6c9328218caac4
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:0b970013351304af46f322da1263516b188318682b2ab1091862497591189ff1
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sat, 01 Oct 2022 16:54:29 +0900
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-lb5bj (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-lb5bj:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age    From               Message
  ----    ------     ----   ----               -------
  Normal  Scheduled  2m48s  default-scheduler  Successfully assigned default/nginx to kube-node2
  Normal  Pulling    2m47s  kubelet            Pulling image "nginx"
  Normal  Pulled     2m32s  kubelet            Successfully pulled image "nginx" in 14.929626927s
  Normal  Created    2m30s  kubelet            Created container nginx
  Normal  Started    2m29s  kubelet            Started container nginx

kubectl edit 명령

kubectl edit pods nginx
$ kubectl edit pods nginx
---
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
  annotations:
    cni.projectcalico.org/containerID: af88356aaf248f17396f20f1dda6c6b912773f493105ff456d5f953af3f6a79c
    cni.projectcalico.org/podIP: 10.233.74.2/32
    cni.projectcalico.org/podIPs: 10.233.74.2/32
  creationTimestamp: "2022-10-01T07:54:10Z"
  labels:
    run: nginx
  name: nginx
  namespace: default
  resourceVersion: "10690"
  uid: 156dbdf9-7267-4ce4-abee-71e8265e210d
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: nginx
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-lb5bj
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: kube-node2
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
...
  - containerID: docker://1a58344645845c0f16e99977d808a57e0ecebf337b9f7d080b6c9328218caac4
    image: nginx:latest
    imageID: docker-pullable://nginx@sha256:0b970013351304af46f322da1263516b188318682b2ab1091862497591189ff1
    lastState: {}
    name: nginx
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2022-10-01T07:54:29Z"
  hostIP: 192.168.56.22
  phase: Running
  podIP: 10.233.74.2
  podIPs:
  - ip: 10.233.74.2
  qosClass: BestEffort
  startTime: "2022-10-01T07:54:10Z"
---
Edit cancelled, no changes made.

 

kubectl run nettool --image ghcr.io/c1t1d0s7/network-multitool -it --rm bash
$ kubectl run nettool --image ghcr.io/c1t1d0s7/network-multitool -it --rm bash
If you don't see a command prompt, try pressing enter.
bash-5.1#

 

kubectl run centos7 --image anti1346/centos:7 -it --rm -- bash
$ kubectl run centos7 --image anti1346/centos:7 -it --rm -- bash
If you don't see a command prompt, try pressing enter.
root@centos7:/$

 

참고URL

- https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-command/

 

728x90

'리눅스' 카테고리의 다른 글

[kubernetes] kubectl delete 명령  (0) 2022.09.22
[kubernetes] minikube addon 설치  (0) 2022.09.21
[kubernetes] kubectl explain 명령  (0) 2022.09.21
[kubernetes] kubectl get events 명령  (0) 2022.09.21
[kubernetes] ReplicationController  (0) 2022.09.21