# Getting Started with Kubernetes: kubectl Cheat Sheet and Working with YAML

> An overview of kubectl, plus common commands and shortcuts for the CKA exam

- URL: https://lcxlab.com/en/post/cka-kubectl-yaml
- Author: Miles Hsu
- Published: 2026-10-13
- Updated: 2026-10-28
- Category: DevOps
- Series: Certified Kubernetes Administrator (CKA) #2
- Tags: CKA, Kubernetes, kubectl
- License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/deed.en)

---

## What is kubectl?

`kubectl` is the official command-line tool provided by Kubernetes. It communicates with the Kubernetes API Server to manage and inspect resources in the cluster.

```mermaid
flowchart TB
    U["User / Administrator"]
    K["kubectl<br/>Command-Line Tool"]
    A["Kubernetes API Server<br/>Authentication, Authorization & Resource Operations"]
    C["Kubernetes Cluster"]
    P["Pods"]
    N["Nodes"]
    S["Services"]

    U --> K
    K <-->|"Kubernetes API"| A
    A <--> C
    C --> P
    C --> N
    C --> S

    classDef client fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef server fill:#dcfce7,stroke:#16a34a,color:#14532d
    classDef cluster fill:#ede9fe,stroke:#7c3aed,color:#4c1d95

    class K client
    class A server
    class C,P,N,S cluster
```
> Figure 1: kubectl Architecture and Workflow

- Common commands:
  
  For example, if you want to check which nodes are in the cluster:
  ```bash
  kubectl get nodes
  ```

  To view the Pods in the current Namespace:
  ```bash
  kubectl get pods
  ```

  To check why a Pod failed to start, or to see its details:
  ```bash
  kubectl describe pod <pod-name>
  ```

All of these commands send requests via kubectl, which are then processed by the Kubernetes API Server.

Note that kubectl itself is not responsible for creating a Kubernetes cluster, nor does it need to be installed on every Node. As long as the host can reach the API Server and has the appropriate kubeconfig and permissions, it can manage the cluster.

---

## How to Install kubectl

My projects are still in the POC (Proof of Concept) stage. I currently have 3 Kubernetes projects that I started myself: two of them are expected to use K3s[^k3s-zh], while a larger one will use RKE2[^rke2-zh], and they all run on Rocky Linux 9. The core of the CKA exam, however, is kubeadm (Vanilla K8s)[^kubeadm-zh], the official standard setup tool. It helps you understand the underlying architecture of Kubernetes, but it is also more complex and requires much more configuration and assembly — a stark contrast to the out-of-the-box nature of the other two.

Here I will use my current workstation OS, Fedora 44, as an example. After all, Fedora is the testing ground for Red Hat Enterprise Linux (RHEL), and Fedora 44 — and the upcoming 45 — are fairly close to RHEL 10[^fedora-rhel-relation].

```mermaid
flowchart TB
    ROOT["Kubernetes Related Tools"]

    ROOT --> M["Cluster Management"]
    ROOT --> B["Cluster Setup"]
    ROOT --> R["Container Runtime"]

    M --> K["kubectl<br/>Manage resources, check status"]

    B --> A["kubeadm<br/>Initialize and join nodes"]
    B --> R2["RKE2<br/>Integrated Kubernetes distribution"]
    B --> S["K3s<br/>Lightweight Kubernetes distribution"]

    R --> C["containerd<br/>Run and manage containers"]
    R --> L["kubelet<br/>Manage Pods on the Node"]

    classDef management fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef distribution fill:#dcfce7,stroke:#16a34a,color:#14532d
    classDef runtime fill:#fef3c7,stroke:#d97706,color:#78350f

    class K management
    class A,R2,S distribution
    class C,L runtime
```

---
### Installing kubectl on Fedora 44

On Fedora 44 (or RHEL / Rocky Linux), the most recommended and standard installation method is to use the DNF RPM repository officially maintained by Kubernetes, which makes future version upgrades very convenient.

#### Step 1: Create the Official Kubernetes DNF Repo

Create and write the official repository configuration file (using **v1.35**, which matches the current CKA exam, as the example):

```bash
cat <<EOF | sudo tee /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://pkgs.k8s.io/core:/stable:/v1.35/rpm/
enabled=1
gpgcheck=1
gpgkey=https://pkgs.k8s.io/core:/stable:/v1.35/rpm/repodata/repomd.xml.key
exclude=kubelet kubeadm kubectl cri-tools kubernetes-cni
EOF
```

#### Step 2: Install kubectl

Install it via the DNF package manager:

```bash
sudo dnf install -y kubectl --disableexcludes=kubernetes
```

#### Step 3: Verify the Installation

Check the `kubectl` client version to make sure the executable works properly:

```bash
kubectl version --client
```

* **Verification**: If the client version is printed successfully (e.g. `Client Version: v1.35.x`), the installation is complete.

---

#### (Optional) Setting Up Autocomplete and Alias

Because `kubectl` commands and flags are fairly long, it is recommended to set up autocompletion and the shorthand alias `k=kubectl` in your everyday shell. This not only makes daily development smoother but also saves a lot of typing.

**1. Zsh (e.g. the default on my Fedora 44 workstation, or macOS)**:

```bash
# 1. Enable kubectl autocompletion
echo 'source <(kubectl completion zsh)' >> ~/.zshrc

# 2. Set the alias k and bind completion to it
echo 'alias k=kubectl' >> ~/.zshrc
echo 'compdef __start_kubectl k' >> ~/.zshrc

# 3. Apply the changes immediately
source ~/.zshrc
```

**2. Bash (e.g. Rocky Linux 9 / RHEL 9 servers)**:

```bash
# 1. Make sure the bash-completion package is installed
sudo dnf install -y bash-completion

# 2. Add autocompletion and the alias k
echo 'source <(kubectl completion bash)' >> ~/.bashrc
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc

# 3. Apply the changes immediately
source ~/.bashrc
```

Exam environment defaults — `alias k=kubectl` is pre-configured:
- The CKA remote terminal (usually Ubuntu/Bash) already has `alias k=kubectl` set up by default.

- Tab completion and alias binding (recommended to add yourself): even though the `k` alias exists by default, `k <Tab>` completion doesn't always work smoothly. I recommend that the very first thing you do in the exam is paste this Bash completion trick into the terminal:

```bash
source <(kubectl completion bash)
alias k=kubectl
complete -o default -F __start_kubectl k
```

Put together, these are the shortcuts commonly used during the exam:

```bash
# View all Pods
k get po

# View a specific Namespace
k get po -n kube-system

# View Pods across all Namespaces
k get po -A

# View nodes
k get no

# Generate YAML without sending a create request
k run nginx --image=nginx --dry-run=client -o yaml

# View command usage
k explain pod
k create deployment --help
```

---

In an air-gapped environment, `pkgs.k8s.io` cannot be reached directly, so the installation method shifts from an "online `dnf` repository" to "**pre-downloading the binary or RPM packages and distributing them manually**".

In addition, **Rocky Linux 9** and **Fedora 44 / RHEL 10** have important system differences in air-gapped environments that deserve special attention (such as default compatibility, cgroup controllers, and SELinux/firewall policies).

---

### Installing `kubectl` in an Air-Gapped Environment

#### Step 1: Pre-download the Binary on an Online Machine

On a machine with internet access, download the `kubectl` binary and checksum file for the matching version (aligned with CKA v1.35):

```bash
# Download the kubectl binary
curl -LO "https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl"

# Download the checksum file and verify
curl -LO "https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl.sha256"
echo "$(cat kubectl.sha256)  kubectl" | sha256sum --check
```

#### Step 2: Copy to the Offline Host and Set Permissions

Transfer `kubectl` to the target Rocky Linux 9 / Fedora 44 host via USB, a bastion host, or an internal artifact registry:

```bash
# Move it into the system executable path and make it executable
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
```

#### Step 3: Verify the Offline Installation

```bash
kubectl version --client
```

---

### Key OS Differences in Air-Gapped Environments (Rocky 9 vs. F44 / RHEL 10)

When deploying in an air-gapped environment, differences in default system behavior directly affect package installation and container dependencies, so pay close attention to them:

| Aspect | Rocky Linux 9 (Enterprise Stable – RHEL 9 based) | Fedora 44 / RHEL 10 (Modern Experimental / Future) |
| --- | --- | --- |
| **Offline Package Dependencies (RPM)** | If you use offline RPM packages (instead of a single binary), Rocky 9 needs **EPEL 9** or a local YUM repo built from the BaseOS / AppStream on the Rocky 9 ISO prepared in advance. | Fedora 44 moves fast and ships newer RPM dependency versions, so **Rocky 9 RPMs cannot be mixed into F44 directly**. |
| **cgroup Driver (cgroup v2)** | Although Rocky 9 enables cgroup v2 by default, some older container runtime scripts may still look for v1; make sure `systemd` is used as the cgroup driver. | Fedora 44 natively uses the latest cgroup v2 integrated with systemd, with no legacy compatibility burden. |
| **SELinux / Firewall (Offline Access)** | Rocky Linux 9 enables hardened **Enforcing SELinux** and `firewalld` by default. In an offline environment, connections to CNI networking or the API Server may fail because they are blocked by policy. | Fedora 44 usually ships the latest SELinux policies, so newer container features work better out of the box. |
| **Container Toolchain (Podman / Containerd)** | Rocky 9 ships the RHEL-family `podman` / `buildah` toolchain by default; to run Kubernetes nodes, you need to package the `containerd` tarball offline. | Fedora 44 includes the latest Podman / Containerd, handy for quick development and validation. |

> 💡 **Rocky Linux 9 Tip**: When deploying in a Rocky Linux 9 air-gapped environment, if you also need to install `kubelet`, be sure to pre-download all dependent RPMs with `dnf-plugins-core` (`dnf download --resolve kubelet`), or simply choose **K3s / RKE2** instead. They bundle all dependencies and the container runtime into a single binary / airgap tarball, neatly avoiding RPM dependency hell on Rocky Linux 9.

---

## YAML Configuration

Early on, I learned from [an Indian guru on YouTube](https://youtu.be/6_gMoe7Ik8k?si=WI5UN5z-FHrKs0z4) that you should make good use of the `--dry-run=client -o yaml` flag with `kubectl run` or `kubectl create` to quickly generate a skeleton, instead of running `touch xxx.yaml && vi xxx.yaml` every time. Here are some handy tricks.

### Pod Quick Generation Template

```bash
k run my-pod --image=nginx --dry-run=client -o yaml > pod.yaml
```
The generated standard Pod YAML looks like this:
```yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: nginx
    image: nginx
```

### Deployment Quick Generation Template

```bash
k create deployment my-deploy --image=nginx --replicas=3 --dry-run=client -o yaml > deploy.yaml
```
The generated standard Deployment YAML looks like this:
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deploy
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-deploy
  template:
    metadata:
      labels:
        app: my-deploy
    spec:
      containers:
      - name: nginx
        image: nginx
```

> 💡 **`--replicas` Version Tip**: `kubectl create deployment` only started supporting the `--replicas` flag in **v1.19**. On older versions (and in some older practice questions), you had to generate the YAML without a replica count and then `vi` it to change `spec.replicas`, or create it first and follow up with `k scale deployment my-deploy --replicas=3`. The exam environment runs a recent version, so just pass `--replicas` when generating the skeleton. One fewer step means a little more time.
>
> ```bash
> # Before v1.19: generate first, then adjust replicas
> k create deployment nginx --image=nginx --dry-run=client -o yaml > nginx-deployment.yaml
> vi nginx-deployment.yaml   # Option 1: edit spec.replicas by hand
> k apply -f nginx-deployment.yaml && k scale deployment nginx --replicas=4   # Option 2: create, then scale
>
> # v1.19+: set replicas while generating
> k create deployment nginx --image=nginx --replicas=4 --dry-run=client -o yaml > nginx-deployment.yaml
> ```

### Service (ClusterIP / NodePort) Quick Generation Template
```bash
# Expose a Deployment as a ClusterIP Service
k expose deployment my-deploy --port=80 --target-port=8080 --dry-run=client -o yaml > svc.yaml

# Create a NodePort Service
k create service nodeport my-svc --tcp=80:80 --dry-run=client -o yaml > nodeport-svc.yaml
```

Of course, there are many other common commands I haven't mentioned; I'm sure you'll discover more while working through practice questions and course labs. Although the exam is open book, time is limited, so it's best to know the common commands inside out and be able to type them from muscle memory. I'll come back and add more if I find other useful ones!

[^k3s-zh]: K3s: A lightweight Kubernetes distribution developed by Rancher that packages its components into a single binary, making it ideal for small POCs, edge computing, and even production environments.

[^rke2-zh]: RKE2: Also known as RKE Government; CIS-compliant by default, combining automation with enterprise-grade security.

[^kubeadm-zh]: kubeadm: The official low-level installation tool (the core of the CKA exam), but CNI and the various components must be configured manually, so maintenance costs are higher.

[^fedora-rhel-relation]: Fedora and RHEL: Fedora is the upstream proving ground where newer kernels, systemd, and package changes are validated first (e.g. F44/F45), and once mature they land in the next major enterprise release (such as RHEL 10 and its downstream-compatible Rocky Linux 10). The Rocky Linux 9 used in my current projects is based on the stable RHEL 9 architecture.

---

References:

[1] Install and Set Up kubectl on Linux - https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/

[2] kubectl Quick Reference - https://kubernetes.io/docs/reference/kubectl/quick-reference/

[3] K3s Documentation - https://docs.k3s.io/

[4] RKE2 Documentation - https://docs.rke2.io/
