Kubernetes Service Accounts: Identity for Your Pods
Service accounts provide identity for pods and control their access to the Kubernetes API.
Default Service Account
Every namespace has a default service account automatically created:
kubectl get serviceaccounts
# NAME SECRETS AGE
# default 0 30dCreating Service Accounts
# Imperative
kubectl create serviceaccount my-sa
# YAML
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-sa
namespace: default
EOFUsing Service Account in Pod
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
serviceAccountName: my-sa
containers:
- name: app
image: my-appToken Mount Path
By default, service account tokens are mounted at:
/var/run/secrets/kubernetes.io/serviceaccount/
├── token
├── ca.crt
└── namespaceDisable Token Auto-Mount
apiVersion: v1
kind: ServiceAccount
metadata:
name: no-token-sa
automountServiceAccountToken: falseOr at pod level:
spec:
automountServiceAccountToken: false
containers:
- name: app
image: my-appService Account with RBAC
Create Role
kubectl create role pod-reader --verb=get,list,watch --resource=podsBind to Service Account
kubectl create rolebinding pod-reader-binding \
--role=pod-reader \
--serviceaccount=default:my-saComplete Example
apiVersion: v1
kind: ServiceAccount
metadata:
name: deployment-manager
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deploy-role
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "create", "update", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: deploy-binding
subjects:
- kind: ServiceAccount
name: deployment-manager
roleRef:
kind: Role
name: deploy-role
apiGroup: rbac.authorization.k8s.ioToken Projection (Kubernetes 1.22+)
spec:
containers:
- name: app
volumeMounts:
- name: token
mountPath: /var/run/secrets/tokens
volumes:
- name: token
projected:
sources:
- serviceAccountToken:
path: token
expirationSeconds: 3600
audience: my-audienceBest Practices
- Create dedicated service accounts per application
- Apply least-privilege RBAC
- Disable token auto-mount when not needed
- Use short-lived projected tokens
- Audit service account usage
Practice Service Accounts
Service accounts appear in CKA and CKS exams. Practice at Sailor.sh.