kubectl basics

kubectl basics

Here are some of the basic kubectl commands.

Installation

sudo apt-get update && sudo apt-get install -y apt-transport-https
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list
sudo apt-get update
sudo apt-get install -y kubectl

Usage

Simple commands to get an overview of the cluster

kubectl cluster-info
kubectl get nodes

Deployments

Create a deployment:

kubectl create deployment POD_NAME --image=IMAGE_NAME

IMAGENAME and PODNAME must not contain underscores. Replace by hyphens.

IMAGE_NAME is an image from a registry, not local.

Alternatively, create a .yml file somewhere and use:

kubectl apply -f [DEPLOYMENT_FILE]

Here is an example file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redblack-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: redblack-deployment
  template:
    metadata:
      labels:
        app: redblack-deployment
    spec:
      containers:
      - name: redblack
        image: 192.168.179.25:5000/redblack:latest
        ports:
        - containerPort: 8051

deployments can be seen using:

kubectl get deployments

Deleting a deployment is as simple as:

kubectl delete deployment deployment-name

Services (deployments that have been exposed)

kubectl expose deployment/DEPLOYMENT_NAME --type="NodePort" --port PORT

Where PORT is the port of the application inside the container

Services can be un-exposed (i.e. deleted) using:

kubectl delete service my-service

Services and deployments can be created by the same yaml file. Simply separate them using ---:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redblack-deployment
spec:
  replicas: 10
  selector:
    matchLabels:
      app: redblack-deployment
  template:
    metadata:
      labels:
        app: redblack-deployment
    spec:
      containers:
      - name: redblack
        image: 192.168.179.25:5000/redblack-stupid:latest
        ports:
        - containerPort: 8051
---
apiVersion: v1
kind: Service
metadata:
  labels:
    run: redblack-service
  name: redblack-service
spec:
  ports:
  - port: 8501
    nodePort: 30111
  selector:
    app: redblack-deployment
  type: LoadBalancer

Accessing a service

Services can be accessed via the port specified as nodeport