Set the default container for kubectl

kubernetes Pod default container kubectl

2 min read | by Jordi Prats

One of the many improvements we get in Kubernetes 1.27 is the ability to set what's the default container:

apiVersion: v1 kind: Pod metadata:  name: multi-container-pod spec:  containers:  - image: alpine:latest  name: one  command:  - sh  - -c  - 'while true; do echo one; sleep 1m; done'  - image: alpine:latest  name: two  command:  - sh  - -c  - 'while true; do echo two; sleep 2m; done'  - image: alpine:latest  name: three  command:  - sh  - -c  - 'while true; do echo tree; sleep 3m; done' 

To do so we just need to use the kubectl.kubernetes.io/default-container annotation setting which one is going to be the default.

Without any annotation it's going to default to the first container that it has in the Pod definition:

$ kubectl logs multi-container-pod Defaulted container "one" out of: one, two, three one 

If we add the annotation setting one of the container names, in this example it's set to two:

apiVersion: v1 kind: Pod metadata:  name: multi-container-pod  annotations:  kubectl.kubernetes.io/default-container: two spec:  containers:  - image: alpine:latest  name: one  command:  - sh  - -c  - 'while true; do echo one; sleep 1m; done'  - image: alpine:latest  name: two  command:  - sh  - -c  - 'while true; do echo two; sleep 2m; done'  - image: alpine:latest  name: three  command:  - sh  - -c  - 'while true; do echo tree; sleep 3m; done' 

Using this annotation we won't get the Defaulted container warning when we are not specifying any container to kubectl. Instead, it will just use the container set in the annotation:

$ kubectl logs multi-container-pod two 

Posted on 01/06/2023

Categories