Imperative Commands with Kubectl

Imperative Commands讲解

While you would be working mostly the declarative way - using definition files, imperative commands can help in getting one time tasks done quickly, as well as generate a definition template easily. This would help save considerable amount of time during your exams.

Before we begin, familiarize with the two options that can come in handy while working with the below commands:

--dry-run: By default as soon as the command is run, the resource will be created. If you simply want to test your command , use the --dry-run=client option. This will not create the resource, instead, tell you whether the resource can be created and if your command is right.

-o yaml: This will output the resource definition in YAML format on screen.

Use the above two in combination to generate a resource definition file quickly, that you can then modify and create resources as required, instead of creating the files from scratch.

Online练习

NOTE: Please remember to use Google Chrome for opening the Quiz Portal. On other browsers it sometime freezes.

Practice Test Link: Udemy Labs - Certified Kubernetes Administrator with Practice Tests Course | KodeKloud

       Welcome to the KodeKloud Hands-On lab                                                           
    __ ______  ____  ________ __ __    ____  __  ______ 
   / //_/ __ \/ __ \/ ____/ //_// /   / __ \/ / / / __ \
  / ,< / / / / / / / __/ / ,<  / /   / / / / / / / / / /
 / /| / /_/ / /_/ / /___/ /| |/ /___/ /_/ / /_/ / /_/ / 
/_/ |_\____/_____/_____/_/ |_/_____/\____/\____/_____/  
                                                        
           All rights reserved                                                                         

controlplane ~ ➜  kubectl create pod nginx-pod --image:nginx:alpine
error: unknown flag: --image:nginx:alpine
See 'kubectl create --help' for usage.

controlplane ~ ✖ kubectl create pod nginx-pod -image:nginx:alpine
error: unknown shorthand flag: 'i' in -image:nginx:alpine
See 'kubectl create --help' for usage.

controlplane ~ ✖ kubectl create pod nginx-pod -image=nginx:alpine
error: unknown shorthand flag: 'i' in -image=nginx:alpine
See 'kubectl create --help' for usage.

controlplane ~ ✖ kubectl run nginx-pod --image=nginx:alpine
pod/nginx-pod created

controlplane ~ ➜  kubectl get pod
NAME        READY   STATUS    RESTARTS   AGE
nginx-pod   1/1     Running   0          5s

controlplane ~ ➜  echo "Deploy a pod named nginx-pod using the nginx:alpine image."
Deploy a pod named nginx-pod using the nginx:alpine image.

controlplane ~ ➜  echo "Deploy a redis pod using the redis:alpine image with the labels set to tier=db."
Deploy a redis pod using the redis:alpine image with the labels set to tier=db.

controlplane ~ ➜  kubectl run --help
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, create a ClusterIP service associated with the pod.  Requires
        `--port`.

    --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. 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).

    --override-type='merge':
        The method used to override the generated object: json, merge, or
        strategic.

    --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 the pod after it exits.  Only valid when attaching to
        the container, e.g. with '--attach' or with '-i/--stdin'.

    --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 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:
        Allocate a TTY for the 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).

controlplane ~ ➜  kubectl run redis --image=redis:alpine --labels="tier=db"
pod/redis created

controlplane ~ ➜  kubectl get pod
NAME        READY   STATUS    RESTARTS   AGE
nginx-pod   1/1     Running   0          2m32s
redis       1/1     Running   0          13s

controlplane ~ ➜  kubectl create service --help
Create a service using a specified subcommand.

Aliases:
service, svc

Available Commands:
  clusterip      Create a ClusterIP service
  externalname   Create an ExternalName service
  loadbalancer   Create a LoadBalancer service
  nodeport       Create a NodePort service

Usage:
  kubectl create service [flags] [options]

Use "kubectl create service <command> --help" for more information about a given
command.
Use "kubectl options" for a list of global command-line options (applies to all
commands).

controlplane ~ ➜  kubectl create service clusterip --help
Create a ClusterIP service with the specified name.

Examples:
  # Create a new ClusterIP service named my-cs
  kubectl create service clusterip my-cs --tcp=5678:8080
  
  # Create a new ClusterIP service named my-cs (in headless mode)
  kubectl create service clusterip my-cs --clusterip="None"

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.

    --clusterip='':
        Assign your own ClusterIP or set to 'None' for a 'headless' service
        (no loadbalancing).

    --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.

    --field-manager='kubectl-create':
        Name of the manager used to track field ownership.

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template,
        go-template-file, template, templatefile, jsonpath, jsonpath-as-json,
        jsonpath-file).

    --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.

    --tcp=[]:
        Port pairs can be specified as '<port>:<targetPort>'.

    --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].

    --validate='strict':
        Must be one of: strict (or true), warn, ignore (or false). "true" or
        "strict" will use a schema to validate the input and fail the request
        if invalid. It will perform server side validation if
        ServerSideFieldValidation is enabled on the api-server, but will fall
        back to less reliable client-side validation if not. "warn" will warn
        about unknown or duplicate fields without blocking the request if
        server-side field validation is enabled on the API server, and behave
        as "ignore" otherwise. "false" or "ignore" will not perform any schema
        validation, silently dropping any unknown or duplicate fields.

Usage:
  kubectl create service clusterip NAME [--tcp=<port>:<targetPort>]
[--dry-run=server|client|none] [options]

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

controlplane ~ ➜  kubectl create service clusterip redis-service --tcp=6379:6379
service/redis-service created

controlplane ~ ➜  kubectl get service
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes      ClusterIP   10.43.0.1       <none>        443/TCP    15m
redis-service   ClusterIP   10.43.134.135   <none>        6379/TCP   7s

controlplane ~ ➜  kubectl describe service redis-service
Name:                     redis-service
Namespace:                default
Labels:                   app=redis-service
Annotations:              <none>
Selector:                 app=redis-service
Type:                     ClusterIP
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.43.134.135
IPs:                      10.43.134.135
Port:                     6379-6379  6379/TCP
TargetPort:               6379/TCP
Endpoints:                
Session Affinity:         None
Internal Traffic Policy:  Cluster
Events:                   <none>

controlplane ~ ➜  kubectl create deployment --help
Create a deployment with the specified name.

Aliases:
deployment, deploy

Examples:
  # Create a deployment named my-dep that runs the busybox image
  kubectl create deployment my-dep --image=busybox
  
  # Create a deployment with a command
  kubectl create deployment my-dep --image=busybox -- date
  
  # Create a deployment named my-dep that runs the nginx image with 3 replicas
  kubectl create deployment my-dep --image=nginx --replicas=3
  
  # Create a deployment named my-dep that runs the busybox image and expose port
5701
  kubectl create deployment my-dep --image=busybox --port=5701
  
  # Create a deployment named my-dep that runs multiple containers
  kubectl create deployment my-dep --image=busybox:latest --image=ubuntu:latest
--image=nginx

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.

    --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.

    --field-manager='kubectl-create':
        Name of the manager used to track field ownership.

    --image=[]:
        Image names to run. A deployment can have multiple images set for
        multi-container pod.

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template,
        go-template-file, template, templatefile, jsonpath, jsonpath-as-json,
        jsonpath-file).

    --port=-1:
        The containerPort that this deployment exposes.

    -r, --replicas=1:
        Number of replicas to create. Default is 1.

    --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.

    --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].

    --validate='strict':
        Must be one of: strict (or true), warn, ignore (or false). "true" or
        "strict" will use a schema to validate the input and fail the request
        if invalid. It will perform server side validation if
        ServerSideFieldValidation is enabled on the api-server, but will fall
        back to less reliable client-side validation if not. "warn" will warn
        about unknown or duplicate fields without blocking the request if
        server-side field validation is enabled on the API server, and behave
        as "ignore" otherwise. "false" or "ignore" will not perform any schema
        validation, silently dropping any unknown or duplicate fields.

Usage:
  kubectl create deployment NAME --image=image -- [COMMAND] [args...] [options]

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

controlplane ~ ➜  echo "Create a deployment named webapp using the image kodekloud/webapp-color with 3 replicas."
Create a deployment named webapp using the image kodekloud/webapp-color with 3 replicas.

controlplane ~ ➜  kubectl create deployment webapp --image=kodekloud/webapp-color --replicas=3
deployment.apps/webapp created

controlplane ~ ➜  kubectl get deployment
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
webapp   3/3     3            3           6s

controlplane ~ ➜  kubectl describe deployment webapp
Name:                   webapp
Namespace:              default
CreationTimestamp:      Sun, 30 Mar 2025 11:48:02 +0000
Labels:                 app=webapp
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=webapp
Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=webapp
  Containers:
   webapp-color:
    Image:         kodekloud/webapp-color
    Port:          <none>
    Host Port:     <none>
    Environment:   <none>
    Mounts:        <none>
  Volumes:         <none>
  Node-Selectors:  <none>
  Tolerations:     <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   webapp-647f97789 (3/3 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  23s   deployment-controller  Scaled up replica set webapp-647f97789 from 0 to 3

controlplane ~ ➜  echo "
> Create a new pod called custom-nginx using the nginx image and run it on container port 8080."

Create a new pod called custom-nginx using the nginx image and run it on container port 8080.

controlplane ~ ➜  kubectl run --help
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, create a ClusterIP service associated with the pod.  Requires
        `--port`.

    --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. 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).

    --override-type='merge':
        The method used to override the generated object: json, merge, or
        strategic.

    --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 the pod after it exits.  Only valid when attaching to
        the container, e.g. with '--attach' or with '-i/--stdin'.

    --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 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:
        Allocate a TTY for the 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).

controlplane ~ ➜  kubectl run custom-nginx --image=nginx --port=8080
pod/custom-nginx created

controlplane ~ ➜  kubectl describe pod custom-nginx
Name:             custom-nginx
Namespace:        default
Priority:         0
Service Account:  default
Node:             controlplane/192.168.187.147
Start Time:       Sun, 30 Mar 2025 11:51:16 +0000
Labels:           run=custom-nginx
Annotations:      <none>
Status:           Running
IP:               10.22.0.14
IPs:
  IP:  10.22.0.14
Containers:
  custom-nginx:
    Container ID:   containerd://34466c474979bd32504ba61361a6f488021e9edabaa226295de6e90e8e931b52
    Image:          nginx
    Image ID:       docker.io/library/nginx@sha256:124b44bfc9ccd1f3cedf4b592d4d1e8bddb78b51ec2ed5056c52d3692baebc19
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sun, 30 Mar 2025 11:51:20 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-vvkw9 (ro)
Conditions:
  Type                        Status
  PodReadyToStartContainers   True 
  Initialized                 True 
  Ready                       True 
  ContainersReady             True 
  PodScheduled                True 
Volumes:
  kube-api-access-vvkw9:
    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  12s   default-scheduler  Successfully assigned default/custom-nginx to controlplane
  Normal  Pulling    12s   kubelet            Pulling image "nginx"
  Normal  Pulled     8s    kubelet            Successfully pulled image "nginx" in 3.548s (3.548s including waiting). Image size: 72180980 bytes.
  Normal  Created    8s    kubelet            Created container: custom-nginx
  Normal  Started    8s    kubelet            Started container custom-nginx

controlplane ~ ➜  echo "Create a new namespace called dev-ns."
Create a new namespace called dev-ns.

controlplane ~ ➜  kubectl namespace dev-ns
error: unknown command "namespace" for "kubectl"

controlplane ~ ✖ kubectl create namespace dev-ns
namespace/dev-ns created

controlplane ~ ➜  kubectl get namespace
NAME              STATUS   AGE
default           Active   22m
dev-ns            Active   6s
kube-node-lease   Active   22m
kube-public       Active   22m
kube-system       Active   22m

controlplane ~ ➜  kubectl create deployment redis-deploy --image=redis --replicas=2 --namespace=dev-ns
deployment.apps/redis-deploy created

controlplane ~ ➜  kubectl get deployment --namespace=dev-ns
NAME           READY   UP-TO-DATE   AVAILABLE   AGE
redis-deploy   2/2     2            2           23s

controlplane ~ ➜  echo "Create a new deployment called redis-deploy in the dev-ns namespace with the redis image. It should have 2 replicas."
Create a new deployment called redis-deploy in the dev-ns namespace with the redis image. It should have 2 replicas.

controlplane ~ ✖ echo "Create a pod called httpd using the image httpd:alpine in the default namespace. Next, create a service of type ClusterIP by the same name (httpd). The target port for the service should be 80."
Create a pod called httpd using the image httpd:alpine in the default namespace. Next, create a service of type ClusterIP by the same name (httpd). The target port for the service should be 80.

controlplane ~ ➜  kubectl run httpd --image=httpd:alpine --port=80
pod/httpd created

controlplane ~ ➜  kubectl create service clusterip httpd --tcp=80:80
service/httpd created

controlplane ~ ➜  kubectl create service --help
Create a service using a specified subcommand.

Aliases:
service, svc

Available Commands:
  clusterip      Create a ClusterIP service
  externalname   Create an ExternalName service
  loadbalancer   Create a LoadBalancer service
  nodeport       Create a NodePort service

Usage:
  kubectl create service [flags] [options]

Use "kubectl create service <command> --help" for more information about a given
command.
Use "kubectl options" for a list of global command-line options (applies to all
commands).

controlplane ~ ➜  kubectl create service clusterip --help
Create a ClusterIP service with the specified name.

Examples:
  # Create a new ClusterIP service named my-cs
  kubectl create service clusterip my-cs --tcp=5678:8080
  
  # Create a new ClusterIP service named my-cs (in headless mode)
  kubectl create service clusterip my-cs --clusterip="None"

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.

    --clusterip='':
        Assign your own ClusterIP or set to 'None' for a 'headless' service
        (no loadbalancing).

    --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.

    --field-manager='kubectl-create':
        Name of the manager used to track field ownership.

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template,
        go-template-file, template, templatefile, jsonpath, jsonpath-as-json,
        jsonpath-file).

    --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.

    --tcp=[]:
        Port pairs can be specified as '<port>:<targetPort>'.

    --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].

    --validate='strict':
        Must be one of: strict (or true), warn, ignore (or false). "true" or
        "strict" will use a schema to validate the input and fail the request
        if invalid. It will perform server side validation if
        ServerSideFieldValidation is enabled on the api-server, but will fall
        back to less reliable client-side validation if not. "warn" will warn
        about unknown or duplicate fields without blocking the request if
        server-side field validation is enabled on the API server, and behave
        as "ignore" otherwise. "false" or "ignore" will not perform any schema
        validation, silently dropping any unknown or duplicate fields.

Usage:
  kubectl create service clusterip NAME [--tcp=<port>:<targetPort>]
[--dry-run=server|client|none] [options]

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

controlplane ~ ➜  kubectl create service clusterip httpd --tcp=80:80 --expose=true
error: unknown flag: --expose
See 'kubectl create service clusterip --help' for usage.

controlplane ~ ✖ kubectl run httpd --image=httpd:alpine --port=80 --expose=true
Error from server (AlreadyExists): pods "httpd" already exists

controlplane ~ ✖ kubectl delete pod httpd
pod "httpd" deleted

controlplane ~ ➜  kubectl run httpd --image=httpd:alpine --port=80 --expose=true
pod/httpd created
Error from server (AlreadyExists): services "httpd" already exists

controlplane ~ ✖ kubectl delete service httpd
service "httpd" deleted

controlplane ~ ➜  kubectl delete pod httpd
pod "httpd" deleted

controlplane ~ ➜  kubectl run httpd --image=httpd:alpine --port=80 --expose=true
service/httpd created
pod/httpd created

controlplane ~ ➜  echo "so just use the --expose and it will auto create the related port expose"
so just use the --expose and it will auto create the related port expose

controlplane ~ ➜  echo "Powered by Moshow@Zhengkai.blog.csdn.net"
Powered by Moshow@Zhengkai.blog.csdn.net

### 命令式学习简介 命令式编程是一种编程范式,在这种范式下,程序由一系列改变状态或执行特定操作的指令组成。命令式学习可以理解为通过具体的编程实践来掌握计算机科学概念和技术的一种方法[^1]。 在命令式学习过程中,学生通常会接触到详细的算法实现过程以及如何利用不同工具完成具体任务。例如,在自然语言处理领域内,可以通过Python及其库如NLTK来进行文本数据的操作与分析;而在机器学习课程中,则可能涉及到使用Octave或MATLAB这样的环境去编写代码并提交作业以巩固所学知识[^2]。 对于希望深入研究命令式学习的人而言,以下是几种有价值的资源: #### 资源推荐 - **书籍** - *《Programming in Python 3》*:这本书不仅涵盖了Python的基础语法,还介绍了面向对象设计模式等内容,非常适合初学者逐步建立起坚实的编程基础。 - **在线教程** - Coursera上的“Machine Learning by Andrew Ng”提供了丰富的视频讲解和练习项目,帮助学员更好地理解和应用各种机器学习技术。 - **开源项目参与** - GitHub上有很多活跃的社区维护着各类有趣的软件工程课题,加入其中不仅可以锻炼实际动手能力,还能与其他开发者交流经验心得。 ```python # 示例:简单的命令式编程风格示例——计算斐波那契数列前n项 def fibonacci(n): result = [] a, b = 0, 1 while len(result) < n: result.append(b) a, b = b, a + b return result print(fibonacci(10)) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值