Перейти к содержанию

Command Reference

Minikube

minikube start
minikube stop

kubectl

kubectl Reference

kubectl Cheat Sheet

# Print the client and server version information
kubectl version

# Display cluster information
kubectl cluster-info

Note

Hierarchy: deploymentreplicasetspods.

Namespace

Get:

kubectl get namespaces
kubectl describe namespaces ns-name
kubectl -n <namespace-name> get pod,svc

Create:

kubectl create -f namespace-dev.yaml
# OR
kubectl create namespace dev  # prod, staging, etc.

Set current context to dev:

kubectl config set-context $(kubectl config current-context) --namespace=dev

Deployments

Strategies

  1. Recreate: take down all old → bring up all newer version = Application downtime.
  2. Rolling update (default): take down old → bring up newer version one by one = No application downtime.

Create

kubectl create -f deployment-definition.yml
kubectl create -f deployment-definition.yml --record  # option adds revision info to the history

kubectl create deployment myapp-deployment --image=busybox
kubectl create deployment myapp-deployment --image=busybox --replicas=3

Get

kubectl get deployments
kubectl get deployments myapp-deployment

kubectl describe deployment myapp-deployment
kubectl describe deployment myapp-deployment | grep -i image

kubectl get replicaset
kubectl get pods
kubectl get all

Update & Scale

kubectl apply -f deployment-definition.yml
kubectl edit deployment myapp-deployment --record

# Use the `--record` flag to save the command used to create/update a deployment against the revision number.
kubectl set image deployment/myapp-deployment nginx=nginx:1.9.1 --record

kubectl scale deployment --replicas=3 myapp-deployment

Status & History

kubectl rollout status deployment/myapp-deployment
kubectl rollout history deployment/myapp-deployment
kubectl rollout history deployment/myapp-deployment --revision=1

Rollback

kubectl rollout undo deployment/myapp-deployment

Delete

kubectl delete deployment myapp-deployment

Edit

Note

With Deployments you can easily edit any field/property of the POD template.

Since the pod template is a child of the deployment specification, with every change the deployment will automatically delete and create a new pod with the new changes.

So if you are asked to edit a property of a POD part of a deployment you may do that simply by running the command:

kubectl edit deployment deployment_name

Replica and Replicaset

Replicaset (new term) or Replication Controller (old term) provides:

  1. High Availability.
  2. Load Balancing & Scaling.

The ReplicaSet provides a state so that a given number of PODs are always online.

replicaset.yaml

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: myapp-replicaset
  labels:
    app: myapp
spec:
  selector:  # section is required in Replicaset
    matchLabels:  # POD labels are indicated
      app: myapp
  replicas: 3  # number of replicas
  template:  # POD template to be replicated
    metadata:
      name: nginx-2
      labels:
        app: myapp
    spec:
      containers:
        - name: nginx
          image: nginx

kubectl commands

For ReplicaSet:

kubectl create -f replicaset.yaml
kubectl get replicaset
kubectl describe replicaset

Edit and apply changes:

kubectl edit replicaset replicaset-1
kubectl replace -f replicaset.yaml
kubectl apply -f replicaset.yaml

Scale:

kubectl scale --replicas=6 -f replicaset.yaml  # will scale even if the yaml is not changed
kubectl scale --replicas=6 replicaset myapp-replicaset  # where, `replicaset` — type, `myapp-replicaset` — name

Delete:

kubectl delete replicaset myapp-replicaset  # Also deletes all underlying PODs

For ReplicationController:

kubectl create -f rc-definition.yml
kubectl get replicationcontroller
kubectl get pods

Service

Create

kubectl create -f service-definition.yaml

Get

kubectl get svc

minikube service myapp-service --url

Pods

kubectl create -f pod-definition.yaml  # default namespace
kubectl create -f pod-definition.yaml --namespace=dev

kubectl replace -f -updated-pod-definition.yaml --force

kubectl get pods  # default namespace
kubectl get pods -o wide
kubectl get pods --namespace=dev  # prod, staging, etc.
kubectl get pods --all-namespaces

kubectl describe pods
kubectl delete pod pod-name

Execute a command in a container inside a pod:

kubectl -n <namespace> exec -it <pod name> -c <container name> bash
kubectl  exec app -c app cat /log/app.log | grep -i login

Edit:

kubectl edit pod <pod name>

Note

Remember, you CANNOT edit specifications of an existing POD other than the below:

  • spec.containers[*].image
  • spec.initContainers[*].image
  • spec.activeDeadlineSeconds
  • spec.tolerations

For example you cannot edit the environment variables, service accounts, resource limits of a running pod.

It may be necessary to recreate the POD in order to edit its definition:

# Extract the pod definition in YAML format to a file.
kubectl get pod pod_name -o yaml > pod_name.yaml

# Edit.
vi pod_name.yaml

# Recreate.
kubectl delete pod pod_name
kubectl create -f pod_name.yaml

Generating Resource Definitions

kubectl Usage Conventions

POD

Create an NGINX Pod:

kubectl run nginx --image=nginx --restart=Never
kubectl run nginx --image=nginx --port=8080
kubectl run nginx --image=nginx --port=8080 --restart=Never

Flag --restart=Never tell Kubernetes to create a single pod rather than a Deployment.

Generate POD Manifest YAML file:

kubectl run nginx-pod --image=nginx --dry-run=client -o yaml > nginx-pod.yaml
Get the documentation for pod manifests:
kubectl explain pods
kubectl explain pod --recursive | less
kubectl explain pod --recursive | grep -A5 tolerations

Output:

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  containers:
    - image: nginx
      name: nginx
      resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

Deployment

Create a deployment:

kubectl create deployment --image=nginx nginx

Generate Deployment YAML file:

kubectl create deployment --image=nginx nginx --dry-run -o yaml

Generate Deployment with 4 Replicas:

kubectl create deployment nginx --image=nginx --replicas=4
kubectl create deployment redis-deploy --image=redis --replicas=2 --namespace=dev

You can also scale a deployment using the kubectl scale command:

kubectl scale deployment nginx --replicas=4

Another way to do this is to save the YAML definition to a file and modify:

kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx-deployment.yaml

Expose:

kubectl expose deployment ingress-controller --type=NodePort --port=80 --name=ingress --dry-run=client -o yaml > ingress.yaml

Service

Create a Service named redis-service of type ClusterIP to expose pod redis on port 6379:

kubectl expose pod redis --port=6379 --name redis-service --dry-run=client -o yaml
This will automatically use the pod's labels as selectors.

OR

kubectl create service clusterip redis --tcp=6379:6379 --dry-run=client -o yaml
This will not use the pods labels as selectors, instead it will assume selectors as app=redis. You cannot pass in selectors as an option. So it does not work very well if your pod has a different label set. So generate the file and modify the selectors before creating the service.

Create a Service named nginx of type NodePort to expose pod nginx's port 80 on port 30080 on the nodes:

kubectl expose pod nginx --port=80 --name nginx-service --type=NodePort --dry-run=client -o yaml
This will automatically use the pod's labels as selectors, but you cannot specify the node port. You have to generate a definition file and then add the node port in manually before creating the service with the pod.

OR

kubectl create service nodeport nginx --tcp=80:80 --node-port=30080 --dry-run=client -o yaml
This will not use the pods labels as selectors.

Both the above commands have their own challenges. While one of it cannot accept a selector the other cannot accept a node port. I would recommend going with the kubectl expose command. If you need to specify a node port, generate a definition file using the same command and manually input the nodeport before creating the service.

Job

kubectl create job <job-name> --image=<image-name> --dry-run=client -o yaml > <job-name>.yaml

Formatting Output

The default output format for all kubectl commands is the human-readable plain-text format.

The -o flag allows us to output the details in several different formats.

kubectl [command] [TYPE] [NAME] -o <output_format>

Here are some of the commonly used formats:

  1. -o json Output a JSON formatted API object.
  2. -o name Print only the resource name and nothing else.
  3. -o wide Output in the plain-text format with any additional information.
  4. -o yaml Output a YAML formatted API object.

ConfigMaps

View:

kubectl get configmaps
kubectl describe configmaps

Create with imperative approach:

kubectl create configmap \
  my_config_map --from-literal=KEY_1=VAL_1 \
                --from-literal=KEY_2=VAL_2

kubectl create configmap \
  my_config_map --from-file=my_config_map.properties

Create with declarative approach:

kubectl create -f my_config_map.yaml

, where my_config_map.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my_config_map
data:
  KEY_1: VAL_1
  KEY_2: VAL_2

Secrets

View:

kubectl get secrets
kubectl describe secrets
kubectl get secret my-app-secret -o yaml

Create with imperative approach:

from-literal:

kubectl create secret generic \
  my-app-secret --from-literal=DB_HOST=postgresql_hostname \
            --from-literal=DB_USER=postgres \
            --from-literal=DB_PASSWORD=hackme

from-literal:

kubectl create secret generic \
  my-app-secret --from-file=my_app_secret.properties

Create with declarative approach:

kubectl create -f my_app_secret_data.yaml

, where my_app_secret_data.yaml:

apiVersion: v1
kind: Secret
metadata:
  name: my-app-secret
data:
  DB_HOST: cG9zdGdyZXNxbF9ob3N0bmFtZQ== # postgresql_hostname
  DB_USER: cG9zdGdyZXM=  # postgres
  DB_PASSWORD: aGFja21l  # hackme

, where the hashes are created like this:

echo -n 'postgresql_hostname' | base64

Also the way Kubernetes handles secrets. Such as:

  1. A secret is only sent to a Node if a Pod on that node requires it.
  2. Kubelet stores the secret into a tmpfs so that the secret is not written to disk storage.
  3. Once the Pod that depends on the secret is deleted, kubelet will delete its local copy of the secret data as well.

Taints and Tolerations

kubectl taint nodes node-name key=value:taint-effect

kubectl taint nodes node1 app=blue:NoSchedule
, where taint-effect (what happens to PODs that DO NOT tolerate this taint?) one of:

  1. NoSchedule — Kubernetes will not schedule the pod onto that node.
  2. PreferNoSchedule — the system will try to avoid placing a pod that does not tolerate the taint on the node, but it is not required.
  3. NoExecute — new PODs will not be scheduled on the node and the existed pods on the node, if any, will be evicted immediately if they do not tolerate the taint.

To remove the taint added by the command above, you can run:

kubectl taint nodes node1 app=blue:NoSchedule-

To check the taint of a node:

kubectl describe node kubemaster | grep Taint
kubectl describe node kubemaster | grep -i taint  # Ignore case.

Node Selectors

To add a label to a node:

kubectl label nodes node-1 size=Large
kubectl label nodes <node-name> <label-key>=<label-value>

Logs

kubectl -n <namespace-name> logs <pod-name> | grep -i <keyword>
kubectl -n <namespace-name> logs <pod-name> <container-name> | grep -i <keyword>
kubectl -n <namespace-name> logs -f <pod-name>  # stream the logs live

Ingress

Reference: ingress

kubectl create ingress <ingress-name> --rule="host/path=service:port"
kubectl create ingress ingress-test --rule="sub.domain.zone/sub*=sub-service:80"
kubectl edit ingress --namespace <ns-name>

kubeconfig & context

To view kubeconfig settings:

cat ./.kube/config
kubectl config view

To get the value from my-kube-config config file like current-context:

kubectl config current-context --kubeconfig my-kube-config
To know the current context:
kubectl config --kubeconfig=/root/my-kube-config current-context

To use that context:

kubectl config --kubeconfig=/root/my-kube-config use-context <context-name>

RBAC

kubectl auth can-i create deployments
kubectl auth can-i delete nodes --as dev-user --namespace staging

Delete all pods in all kubernetes namespaces

kubectl delete --all pods --namespace=foo
kubectl delete --all deployments --namespace=foo
kubectl delete --all namespaces
for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system);
do
  kubectl delete ns $each
done

See this stackoverflow question.