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