Skip to main content

Using Advanced kubectl Techniques

1. Using JSONPath Queries

JSONPath Expression Description Example Output
$.items[*].metadata.name Retrieves names of all items in the list ["pod1" "pod2" "pod3"]
$.items[0].spec.containers[*].name Gets names of containers from the first item ["nginx" "redis"]
$.items[*].status.phase Retrieves status phase of all items ["Running" "Pending" "Succeeded"]
$.items[*].metadata.labels.app Extracts app label from metadata of all items ["frontend" "backend" "database"]

Example: Filtering Pods by Label

kubectl get pods -o jsonpath='{.items[*].metadata.name}' --selector=app=frontend

Example: Getting Container Image Names

kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
Note: JSONPath expressions must be enclosed in single quotes to avoid shell interpretation.

2. Using Custom Columns

Field Description Example
.metadata.name Name of the resource my-pod
.spec.containers[0].image First container's image nginx:latest
.status.phase Current phase of pod Running
.metadata.creationTimestamp Time resource was created 2025-04-01T12:34:56Z

Example: Custom Columns with kubectl get

kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image,STATUS:.status.phase
Note: Custom columns support JSONPath expressions for flexible field selection.

3. Formatting Output

Format Description Usage
json JSON format output kubectl get pods -o json
yaml YAML format output kubectl get pods -o yaml
name Names only kubectl get pods -o name
wide Additional fields kubectl get pods -o wide
custom-columns Custom column layout kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

Example: Custom Columns Output

kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NAMESPACE:.metadata.namespace</code>
</pre>
</div>
</div>
<div class="example">
<h2 id="example-json-output">Example: JSON Output<a href="#example-json-output" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<div class="codeBlock" data-language="bash">
<pre><code>kubectl get pod my-pod -o json</code>
</pre>
</div>
</div>
<h2 id="4-using-field-selectors">4. Using Field Selectors<a href="#4-using-field-selectors" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<table>
<tbody>
<tr>
<th>Field Selector</th>
<th>Description</th>
<th>Examples</th>
</tr>
<tr>
<td class="property">metadata.name</td>
<td>Selects resources by name</td>
<td><code>name=my-pod</code></td>
</tr>
<tr>
<td class="property">metadata.namespace</td>
<td>Selects resources by namespace</td>
<td><code>namespace=default</code></td>
</tr>
<tr>
<td class="property">spec.nodeName</td>
<td>Selects pods by the node they are scheduled on</td>
<td><code>spec.nodeName=node-1</code></td>
</tr>
<tr>
<td class="property">status.phase</td>
<td>Selects pods by their current phase</td>
<td><code>status.phase=Running</code></td>
</tr>
<tr>
<td class="property">status.podIP</td>
<td>Selects pods by their IP address</td>
<td><code>status.podIP=10.244.0.5</code></td>
</tr>
</tbody>
</table>
<div class="example">
<h2 id="example-filtering-pods-by-status-phase">Example: Filtering Pods by Status Phase<a href="#example-filtering-pods-by-status-phase" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<div class="codeBlock" data-language="bash">
<pre><code>kubectl get pods --field-selector=status.phase=Running

Example: Filtering Pods by Node Name

kubectl get pods --field-selector=spec.nodeName=node-1
Note: Field selectors can be combined using comma separation, e.g., --field-selector=metadata.namespace=default,status.phase=Running.

5. Using Label Selectors

Selector Type Description Examples
Equality-based Selectors Match labels with exact key-value pairs environment=production, app=nginx
Set-based Selectors Match labels using set operations (in, notIn, exists, doesNotExist) environment in (production, staging), version notIn (v1.0, v1.1)
Multiple Label Selectors Combine multiple selectors with comma (AND logic) environment=production,app=nginx

Example: Label Selectors in kubectl

kubectl get pods -l environment=production
kubectl get pods -l 'environment in (production, staging)'
kubectl get pods -l 'version notIn (v1.0, v1.1)'
kubectl get pods -l environment=production,app=nginx
Note: Label selectors are used in various kubectl commands like get, delete, describe, and rollout.
Warning: Ensure labels are consistently applied across resources to avoid unexpected selection behavior.

6. Performing Bulk Operations

Example: Apply Configuration to Multiple Resources

kubectl apply -f config.yaml --all
Operation Description Flags Notes
kubectl apply Applies configuration from files or directories --all Applies to all resources in the directory
kubectl patch Updates resources with JSON patches --type, --patch Useful for bulk updates to labels or annotations
kubectl edit Edits resources in the default editor --output Can be used in scripts for bulk editing

Example: Update Labels on Multiple Pods

kubectl label pods --all env=production

Example: Delete Multiple Resources by Label

kubectl delete pods -l app=frontend

7. Using kubectl patch

The kubectl patch command allows you to update resources in your Kubernetes cluster by applying changes directly to the resource's configuration. It supports different patch strategies and is useful for making targeted updates without replacing the entire resource.

Option Values Description
--type strategic, merge, json Specifies the patch strategy to use. Default is strategic.
--patch <json-patch> The JSON patch or merge patch to apply. Required for json and merge strategies.
--local true, false If set to true, patches a local file instead of applying to the cluster.

Example: Patching a Deployment's Replicas

kubectl patch deployment my-deployment -p '{"spec":{"replicas":5}}'

Example: Patching with Strategic Merge

kubectl patch deployment my-deployment --type strategic -p '{"spec":{"template":{"spec":{"containers":[{"name":"app","image":"nginx:1.25"}]}}}}'
Note: The --type strategic is the default and supports more complex structures like lists. For simple key-value updates, merge or json can be used.
Warning: Patching resources can cause unintended side effects if not done carefully. Always verify the patch before applying it in production.

8. Creating Resources from stdin

Use kubectl create or kubectl apply with the -f - flag to create Kubernetes resources from stdin. This is useful for piping resource definitions or applying configurations dynamically.

Command Description Example
kubectl create -f - Creates resources from stdin
echo 'apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: app
    image: nginx' | kubectl create -f -
kubectl apply -f - Applies resources from stdin, updating existing ones cat config.yaml | kubectl apply -f -

Example: Creating a Pod from stdin

echo 'apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80' | kubectl create -f -
Note: Ensure the input is valid YAML or JSON for Kubernetes resources.

9. Using kubectl diff

The kubectl diff command allows you to compare the current state of a resource with its desired state as defined in a configuration file. This is particularly useful for identifying changes before applying them.

Option Values Description
kubectl diff -f <filename> Compare the current state of a resource with the desired state from a file
kubectl diff --namespace <namespace> Specify the namespace to compare resources in
kubectl diff --output <format> Specify the output format (e.g., json, yaml)

Example: Comparing a Deployment Configuration

kubectl diff -f deployment.yaml
Note: The kubectl diff command requires the kubectl plugin to be installed and configured properly.
Warning: Ensure that the configuration file used with kubectl diff is up-to-date to avoid misleading comparisons.

10. Using kubectl wait

The kubectl wait command is a powerful utility that allows you to wait for a Kubernetes resource to reach a specified condition. It's particularly useful in automation scripts and CI/CD pipelines where you need to ensure that resources are in a particular state before proceeding.

Option Values Description
--for condition=Ready, jsonpath={.status.phase}=Running Specifies the condition to wait for. Can be a condition name or a JSONPath expression.
--timeout 30s, 5m Timeout for the wait command. Defaults to 0 (no timeout).
--output json, yaml Output format for the resource once it reaches the desired state.

Example: Waiting for a Pod to be Ready

kubectl wait --for=condition=Ready pod/my-pod --timeout=30s

Example: Waiting for a Deployment to be Available

kubectl wait --for=condition=Available deployment/my-deployment --timeout=2m
Note: The --for=condition=Ready option is commonly used for pods and other resources that support readiness conditions.
Warning: If the timeout is exceeded, kubectl wait will return a non-zero exit code. This can be used in scripts to handle timeouts gracefully.

11. Creating Dry Runs

Example: Dry Run Deployment

kubectl create deployment my-app --image=nginx --dry-run=client -o yaml
Flag Description Values
--dry-run Simulates the action without actually performing it client, server
-o yaml Output format as YAML yaml, json
Note: --dry-run=client is faster and does not require server interaction, while --dry-run=server validates against the API server.
Warning: Dry runs do not execute the actual command, so they cannot be used to test runtime behavior or side effects.

12. Using kubectl explain

The kubectl explain command provides detailed information about Kubernetes resources, their fields, and their structure. It's particularly useful for understanding the schema of resources without having to consult external documentation.

Resource Field Description Example
apiVersion v1 API version of the resource apiVersion: v1
kind Pod Type of Kubernetes resource kind: Pod
metadata.name my-pod Name of the resource
metadata:
  name: my-pod

Example: Explaining a Pod resource

kubectl explain pod

Example: Explaining a specific field in a Pod

kubectl explain pod.spec.containers
Note: The kubectl explain command can be used with any Kubernetes resource, including custom resources defined by CRDs.
Warning: If a resource is not installed or is not available in the current cluster, kubectl explain will return an error.

Was this article helpful?