---
# System prepended metadata

title: '[k8s] Labels & Selectors & Annotations'
tags: [scheduling, kubernetes]

---

[k8s] Labels & Selectors & Annotations
========
###### tags: `kubernetes` `scheduling`

## labels
```yaml=
# pod-definition.yaml
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
    type: frontend
spec: 
  containers: 
  - name: nginx-container
    image: nginx
    ports:
    - containerPort: 8080
```
```shell=
kubectl get pods --selector app=myapp,tier=frontend
# or use --label
kubectl get pods --label app=myapp,tier=frontend
# or
kubectl get pods -l app=myapp -l tier=frontend
```

`-l, --selector=''`：
+ Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints.

```shell=
kubectl delete deployment,services,statefulsets -l 'environment in (local,dev,staging)'
```

## selectors + matchLabels
![](https://i.imgur.com/rayIY6F.jpg =400x)

![](https://i.imgur.com/t6pp4Iy.jpg =400x)

## Annotations

:::success
+ The main difference between labels and annotations is that annotations are ***not used*** to filter, group, or operate over the Kubernetes resource. 
+ Instead, you can use them to access ***additional*** information about it.
:::
> labels and selectors are used to group objects
> > annotations are used to record other details for informatry purpose

```yaml=
# replicaset-definition.yaml
apiVersion:
kind: ReplicaSet
metadata:
  name: simple-webpp
  labels:
    app: App1
    function: front-end
  annotations:
    buildVersion: 1.34
spec:
  replicas: 3
  selector:
    matchLabels:
      app: App1
  template:
    medata:
      labels:
        app: App1
        function: front-end
    spec:
      containers:
      - name: simple-webapp
        image: simple-webapp
```
## references
+ [Kubernetes Labels: Expert Guide with 10 Best Practices ](https://cast.ai/blog/kubernetes-labels-expert-guide-with-10-best-practices)