Try Sailor Cloud - 25% off!

Claim Now
Back to all posts

Kubernetes Service Accounts: Identity for Your Pods

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         30d

Creating Service Accounts

# Imperative
kubectl create serviceaccount my-sa

# YAML
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-sa
  namespace: default
EOF

Using Service Account in Pod

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  serviceAccountName: my-sa
  containers:
  - name: app
    image: my-app

Token Mount Path

By default, service account tokens are mounted at:

/var/run/secrets/kubernetes.io/serviceaccount/
├── token
├── ca.crt
└── namespace

Disable Token Auto-Mount

apiVersion: v1
kind: ServiceAccount
metadata:
  name: no-token-sa
automountServiceAccountToken: false

Or at pod level:

spec:
  automountServiceAccountToken: false
  containers:
  - name: app
    image: my-app

Service Account with RBAC

Create Role

kubectl create role pod-reader --verb=get,list,watch --resource=pods

Bind to Service Account

kubectl create rolebinding pod-reader-binding \
  --role=pod-reader \
  --serviceaccount=default:my-sa

Complete 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.io

Token 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-audience

Best Practices

  1. Create dedicated service accounts per application
  2. Apply least-privilege RBAC
  3. Disable token auto-mount when not needed
  4. Use short-lived projected tokens
  5. Audit service account usage

Practice Service Accounts

Service accounts appear in CKA and CKS exams. Practice at Sailor.sh.

Start Free Practice