ServiceAccounts
A ServiceAccount provides an identity for processes running in a Pod.
- Every namespace has a
defaultServiceAccount - Pods that do not specify a ServiceAccount use the
defaultone - ServiceAccounts are used to authenticate against the Kubernetes API and external services
More Information
Creating a ServiceAccountโ
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-app-sa
namespace: my-namespace
Or via CLI:
kubectl create serviceaccount my-app-sa -n my-namespace
Using in a Podโ
spec:
serviceAccountName: my-app-sa
containers:
- name: app
image: my-app:latest
- The ServiceAccount token is automatically mounted at
/var/run/secrets/kubernetes.io/serviceaccount/ - To opt out of automatic mounting:
automountServiceAccountToken: false
Granting Permissionsโ
ServiceAccounts on their own have no permissions. Use RBAC to grant access:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: my-app-binding
namespace: my-namespace
subjects:
- kind: ServiceAccount
name: my-app-sa
namespace: my-namespace
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
Image Pull Secretsโ
ServiceAccounts can hold image pull secrets for pulling images from private registries:
kubectl create secret docker-registry regcred \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-app-sa
imagePullSecrets:
- name: regcred
All Pods using this ServiceAccount will automatically use the registry credentials.
More Information
Token Projectionโ
- Kubernetes 1.22+ uses bound service account tokens by default (short-lived, audience-scoped)
- Tokens are projected into the Pod and automatically rotated
- More secure than the legacy long-lived tokens