How can I specify the number of instances in container level (same pod) without duplicating code in my yaml file? Example:
spec:
containers:
- name: app-a
image: image-a
- name: app-b
image: image-b
- name: app-c-1
image: image-c
- name: app-c-2
image: image-c
- name: app-c-3
image: image-c
You can see app-c
is duplicated. How can I avoid that?
There is no way to do this with K8s manifests.
I recommend you let the duplicated containers run in a separate Deployment or ReplicaSet.
Typically you would use a Deployment to specify this. That includes a replicas:
field that you can change dynamically.
apiVersion: v1
kind: Deployment
metadata:
name: c
spec:
replicas: 3 # <--
template:
spec:
containers:
- name: c
image: image-c
You will also need a corresponding Service, which in turn requires adding appropriate labels to the pod template.
The approach you're describing actually won't work. Say image-c listens on port 3000. Since every container in a pod shares the same network namespace, all of the containers will try to listen on the pod's port 3000, but only one can succeed.
There are some standard reasons to prefer Deployments over Pods. You can't change the replica count in your proposed setup without completely deleting and recreating the pod; and when you do this, you also will stop the unaffected containers a
and b
. With a Deployment you can kubectl scale deployment c --replicas=5
and it will start up two new pods without affecting anything else.