Version note: examples use the Kubernetes v1.35 documentation snapshot, not necessarily the newest release. Check current support and component compatibility. These commands were not tested on a live cluster.
What this guide covers
A Kubernetes YAML file describes a resource you want the cluster to manage. A Deployment keeps application Pods running; a Service sends traffic to selected Pods. Labels connect these resources.
Before you start
Use a working test cluster and kubectl with the intended context selected. YAML indentation uses spaces. The examples create a namespace, a Deployment and a Service.
Step 1: Create a namespace
A namespace groups related resources. Save this as namespace.yaml, then run kubectl apply -f namespace.yaml:
apiVersion: v1
kind: Namespace
metadata:
name: yaml-lab
labels:
purpose: learning
Step 2: Describe the application
Save this as web.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: yaml-lab
labels:
owner: platform
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.28.0
ports:
- name: http
containerPort: 80
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
apiVersion selects the API, kind selects the resource type, and metadata gives its name and namespace. spec describes the requested configuration. The Pod template belongs under spec.template. Do not copy server-generated status fields into a new file.
Step 3: Add the Service
Append this YAML document to web.yaml after a --- separator:
apiVersion: v1
kind: Service
metadata:
name: frontend
namespace: yaml-lab
spec:
type: ClusterIP
selector:
app: web
ports:
- name: http
port: 80
targetPort: http
The Service selects Pods by labels, not by matching the Deployment name. Its targetPort must match the application’s listening port or named port.
Step 4: Validate and apply
Run:
kubectl explain deployment.spec.template.spec.containers --api-version=apps/v1
kubectl apply --dry-run=server -f web.yaml
kubectl diff -f web.yaml
kubectl apply -f web.yaml
kubectl -n yaml-lab get deployment,replicaset,pod,service
kubectl -n yaml-lab get endpointslices -l kubernetes.io/service-name=frontend
A server-side dry run validates the request without saving it. kubectl diff shows changes and returns exit code 1 when differences exist. Applying a valid file does not guarantee the image starts successfully.
Check the result
Check the Deployment rollout, Pod readiness and Service EndpointSlices. A Service with no ready endpoints may have a wrong selector or unhealthy Pods.
Conversation
0 commentsNo comments yet. Start the conversation below.