Entity Relationships: How Pod, Service, Deployment, and Node Connect¶
Igor Gorovyy
DevOps Engineer Lead & Senior Solutions Architect
The last article of the series. Here we put it all together: five resource types, how they relate, how the data sits in BoltDB, and why the model looks the way it does.
ER Diagram¶
erDiagram
DEPLOYMENT ||--o{ POD : "manages via labels"
DEPLOYMENT {
string name PK
string namespace
string uid
int replicas
map selector
PodTemplate template
DeploymentStatus status
}
POD ||--|{ CONTAINER_STATUS : contains
POD {
string name PK
string namespace
string uid
map labels
PodPhase phase
string node_name FK
string pod_ip
string host_ip
}
CONTAINER_STATUS {
string name
string container_id FK
bool ready
string state
int exit_code
}
SERVICE ||--o{ POD : "selects via labels"
SERVICE {
string name PK
string namespace
map selector
ServicePort[] ports
string[] endpoints
}
NODE ||--o{ POD : "runs"
NODE {
string name PK
map labels
string address
NodeCondition condition
int pod_count
datetime last_heartbeat
}
EVENT {
string type
string reason
string message
string object FK
datetime timestamp
}
POD }o--|| NODE : "scheduled on"
SERVICE }o--o{ POD : "routes to matching"
EVENT }o--|| POD : "about"
EVENT }o--|| NODE : "about"
EVENT }o--|| DEPLOYMENT : "about"
Three Types of Relationships¶
1. Through labels¶
Deployment -> Pods and Service -> Pods work through label selectors. The mechanism itself was covered in Label Selectors and Service Discovery; here is how it looks inside the controllers:
// ReplicationController finds a Deployment's pods
func (rc *ReplicationController) reconcileDeployment(
dep *Deployment) {
allPods, _ := rc.store.ListPods(dep.Metadata.Namespace)
var matchingPods []*Pod
for _, pod := range allPods {
if matchLabels(pod.Metadata.Labels,
dep.Spec.Selector) {
matchingPods = append(matchingPods, pod)
}
}
// current vs desired...
}
// ServiceController finds a Service's pods
func (sc *ServiceController) reconcileService(svc *Service) {
pods, _ := sc.store.ListPods(svc.Metadata.Namespace)
var endpoints []string
for _, pod := range pods {
if matchLabels(pod.Metadata.Labels,
svc.Spec.Selector) &&
pod.Status.Phase == PodRunning &&
pod.Status.PodIP != "" {
for _, port := range svc.Spec.Ports {
endpoints = append(endpoints,
fmt.Sprintf("%s:%d",
pod.Status.PodIP, port.TargetPort))
}
}
}
svc.Status.Endpoints = endpoints
}
There are no foreign keys here. A Deployment doesn't store a list of its pods; it looks them up through the selector every time.
What that means in practice:
- A pod gets recreated with a new UID - nothing to update, the labels are the same.
- Put
app=webon a pod you created by hand, and on the next reconcile it's in the Service's endpoints. - The Deployment and the Service know nothing about each other, even though they look at the same pods.
graph TB
DEP["Deployment: web<br/>selector: app=web, tier=frontend"]
SVC["Service: web-svc<br/>selector: app=web"]
P1["Pod: web-0<br/>labels: app=web, tier=frontend"]
P2["Pod: web-1<br/>labels: app=web, tier=frontend"]
P3["Pod: debug<br/>labels: app=web, tier=debug"]
P4["Pod: api-0<br/>labels: app=api"]
DEP -->|"match (app=web AND tier=frontend)"| P1
DEP -->|"match"| P2
DEP -.->|"no match (tier!=frontend)"| P3
SVC -->|"match (app=web)"| P1
SVC -->|"match"| P2
SVC -->|"match"| P3
SVC -.->|"no match"| P4
Look at the debug pod. The Service with selector app=web sees both the Deployment's pods and the debug pod created by hand. The Deployment with app=web, tier=frontend sees only its own. Same labels, different sets of pods, because the selectors differ.
2. Direct reference (Pod -> Node)¶
pod.Spec.NodeName = selected.Metadata.Name
The Scheduler writes the node name straight into the Pod spec. The Agent filters on it:
func (a *Agent) reconcilePods() {
pods, _ := a.listMyPods()
for _, pod := range pods {
if pod.Spec.NodeName != a.nodeName {
continue // not my pod
}
// ...
}
}
3. Text reference (Events -> anything)¶
type Event struct {
Type string `json:"type"`
Reason string `json:"reason"`
Message string `json:"message"`
Object string `json:"object"` // "pod/web-0"
Timestamp time.Time `json:"timestamp"`
}
Object is a plain string: "pod/web-0", "node/node-1", "deployment/web". Nothing checks that the object exists. For an event log that's enough; the log itself is covered in Event System.
Namespace Scoping¶
Not all resources live in a namespace:
| Resource | Namespaced? | BoltDB key format |
|---|---|---|
| Pod | Yes | {namespace}/{name} -> default/web-0 |
| Service | Yes | {namespace}/{name} -> default/web-svc |
| Deployment | Yes | {namespace}/{name} -> default/web |
| Node | No | {name} -> node-1 |
| Event | No | {timestamp}-{object} -> 1714300000-pod/web-0 |
func nsKey(namespace, name string) []byte {
if namespace == "" {
namespace = "default"
}
return []byte(namespace + "/" + name)
}
Filtering by namespace is a prefix match on BoltDB keys:
func (s *Store) list(bucket []byte, prefix string,
fn func([]byte) error) error {
return s.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
return b.ForEach(func(k, v []byte) error {
if prefix == "" ||
strings.HasPrefix(string(k), prefix+"/") {
return fn(v)
}
return nil
})
})
}
ListPods("") - all pods. ListPods("staging") - only pods in the staging namespace.
Full Data Flow Picture¶
graph TB
subgraph "User"
APPLY["sheepctl apply deployment.json<br/>{replicas: 3, selector: app=web}"]
end
subgraph "API Server"
CREATE_DEP["Create Deployment<br/>key: default/web"]
end
subgraph "ReplicationController"
RC["Find pods where labels match app=web<br/>Current: 0, Desired: 3<br/>Create: web-0, web-1, web-2"]
end
subgraph "Scheduler"
S["Find pending pods without NodeName<br/>Filter nodes: Ready, heartbeat fresh, resources OK<br/>Score: least-loaded wins<br/>Assign: web-0->node-1, web-1->node-2, web-2->node-1"]
end
subgraph "Agent (node-1)"
A1["Find pods where NodeName=node-1<br/>web-0: Pending -> Create+Start containers<br/>web-2: Pending -> Create+Start containers<br/>Update: Phase=Running, PodIP=10.20.0.x"]
end
subgraph "ServiceController"
SCC["Find service: web-svc, selector: app=web<br/>Find Running pods matching selector<br/>Endpoints: [10.20.0.2:8080, 10.20.0.3:8080, 10.20.0.4:8080]"]
end
APPLY --> CREATE_DEP
CREATE_DEP --> RC
RC --> S
S --> A1
A1 --> SCC
Each step of this diagram had its own article: API Server, Replication Controller, Scheduler, Pod Lifecycle, Service Discovery.
Series Wrap-up¶
Forty articles, three systems.
Sheep (parts 1-10) - container runtime:
- Linux namespaces for process isolation
- Re-exec pattern, because Go and
clone()don't get along - pivot_root for a root filesystem of its own
- Cgroups v2 for memory, CPU and PID limits
- OverlayFS for copy-on-write layers
- Bridge networking and NAT with iptables
- Image management
- Container lifecycle
- A CLI in 500 lines
Shepherd (parts 11-20) - orchestrator:
- REST API Server on
net/http - BoltDB instead of etcd
- Scheduler with Filter + Score
- Reconciliation loop and Replication Controller
- Service discovery through labels
- Node health on heartbeats
- Node agent, the kubelet counterpart
- Pod lifecycle from Pending to Running
- Event system
Meadow (parts 21-24) - OCI image registry:
- OCI Distribution Spec
- Content-addressable storage
- Pull from Docker Hub with auth and multi-arch
- Push to your own registry
Patterns and Go (parts 25-40):
- Desired state vs actual state
- Label selectors instead of foreign keys
- Async scheduling
- Graceful shutdown
- Two-mode architecture
- Embedded vs external DB
- Go: build tags, syscalls, goroutines for control loops, CLI without frameworks, JSON for state
- Comparisons: Docker vs Sheep, Kubernetes vs Shepherd
- Filesystem layout, state machines and this article
About 5000 lines of Go on the same kernel primitives Docker and Kubernetes use. It won't become a production runtime, but it was enough for me to see what happens under docker run and kubectl apply.
Worth Knowing¶
Label matching is a full O(n) scan on every reconcile. At 10,000 pods you'll notice it. Kubernetes controllers don't hit the API on every pass: they read from a local informer cache and can add their own indexes to it. Shepherd goes to BoltDB every time, and for a few dozen resources that's fine.
Two more things show up as the cluster grows:
- Nobody checks for overlapping selectors. Two Deployments with overlapping selectors start "stealing" each other's pods: on every reconcile each sees the other's pods as its own. Kubernetes partly guards against this with ownerReferences; Shepherd has no such protection.
- Events grow without limit. The
{timestamp}-{object}key is never overwritten and there's no GC. On a busy cluster the events bucket keeps inflatingshepherd.db.
Fun Facts¶
- Label selectors in Kubernetes go beyond equality: there's
in,notin,exists(e.g.tier in (frontend, backend)). Shepherd only supports exact key=value matching. That was enough for the examples in this series. - A Service in Kubernetes doesn't know about pods directly. Between them sits a separate Endpoints object, now EndpointSlice (GA since 1.21), filled in by its own controller. Shepherd folded this into a single
Status.Endpointsfield. - EndpointSlice exists because of large services. The old Endpoints was one object holding every address, and any change to one pod rewrote the whole thing and pushed it to every node. A slice holds up to 100 addresses by default, so only one chunk changes.
ownerReferencesare what turn on cascading deletion: delete a Deployment and the garbage collector removes its ReplicaSets and pods.kubectl delete deployment web --cascade=orphandoes the opposite and leaves the pods running. Shepherd behaves like the second case, without a choice.- To keep a Deployment's ReplicaSets from sharing pods, Kubernetes adds a
pod-template-hashlabel to them - a hash of the pod template. That gives each revision its own non-overlapping selector. - In
apps/v1a Deployment's selector can't be changed after creation. Otherwise one selector edit would cut off all existing pods and create new ones. - Labels in Kubernetes came out of pain with Borg. There a job was identified by its name, and users stuffed metadata into names up to 180 characters long, then parsed them with regexes. The Borg and Kubernetes authors describe this in "Borg, Omega, and Kubernetes" (2016).
- Node isn't namespaced for a reason: a namespace is a boundary for names and RBAC, and a node is physical and shared by the whole cluster.
kubectl api-resources --namespaced=falselists the cluster-scoped resources. Events in Kubernetes, unlike Shepherd, are namespaced. - Kubernetes solved the endless-events problem simply: kube-apiserver keeps events for an hour (
--event-ttl, default1h), then etcd deletes them on its own. - The ER model itself comes from Peter Chen's 1976 paper in ACM TODS. The "crow's foot" line ends that Mermaid draws in
erDiagramwere introduced by Gordon Everest the same year.
What I figured out while digging into this¶
What got me most was dropping foreign keys. At first it seemed odd: how can you not store which pods belong to a Deployment? Then a pod got recreated with a new UID, the Service and Deployment kept finding it by labels, and nothing had to be updated. The relationship is computed every time, so it has no way to go stale.
But you pay for it in guarantees. Nothing stops two controllers from treating the same pod as theirs. Kubernetes closes that gap with ownerReferences, and now I see why that complexity is there.
What could be improved¶
- An index by labels (at least
map[labelKey][]podID) so reconcile doesn't scan every pod. That's the first step toward what informers do. - ownerReferences and cascading deletion, so deleting a Deployment removes its pods instead of leaving orphans.
- A watch stream instead of a full reconcile: the controller reacts to a specific change rather than re-reading the whole state every N seconds.
- TTL and GC for Events: cap the bucket by age or count so
shepherd.dbdoesn't grow forever.
Try It Yourself¶
git clone https://github.com/igorgorovoy/sheep-shepherd-meadow && cd sheep-shepherd-meadow
go build ./...
# Start everything and experiment:
sudo ./shepherd --mode standalone &
sheepctl apply -f examples/deployment.json
sheepctl get pods && sheepctl get services && sheepctl events
This is the last article in the series. To go through it from the start, part one is Linux Namespaces.
Resources¶
- Kubernetes API concepts: owner references, finalizers, resource relationships
- ReplicaSet: an example of parent-child entities
- Labels and Selectors: label syntax and set-based selectors
- Owners and Dependents: ownerReferences and cascading deletion
- EndpointSlices: why Endpoints was split into chunks
- Namespaces: which resources are namespaced and which aren't
- kube-apiserver flags:
--event-ttland the rest - Borg, Omega, and Kubernetes: where labels came from
- Chen, The Entity-Relationship Model (1976): the original ER model paper
- Mermaid: Entity Relationship Diagrams: syntax for the diagram in this article
Source code for the series: github.com/igorgorovoy/sheep-shepherd-meadow
Previous: State Machines | First: Linux Namespaces
