create Replicaset with separate pods in Kubernetes

1/16/2021

I want to create a ReplicaSet with separate pods.

Pods

apiVersion: v1
kind: Pod
metadata:
  name: user-pod
  labels:
    app: user-pod
spec:
  containers:
    - name: user-container
      image: kia9372/store-user

Replicaset

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: user-replicaset
  labels:
    app: user-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-pod

but when i execute the following command, it throws the foloowing error:

kubectl create -f user-replicaset.yml 
 
>error: error validating "user-replicaset.yml": 
error validating data: ValidationError(ReplicaSet.spec.selector): 
unknown field "app" in io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector; 
if you choose to ignore these errors, turn validation off with --validate=false

What's the problem? how can I solve this?

-- Mr-Programer
kubernetes
minikube

3 Answers

1/16/2021

matchlabels is missing. Also your pod definition does not define a matching label.

Have a look at the docs for a proper setup: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/

-- Aydin K.
Source: StackOverflow

1/16/2021

Did you try adding that label also in Replicaset :

apiVersion: apps/v1
kind: ReplicaSet    
metadata:
  labels:
    app: user-replicaset
    app: user-pod

This example uses that label in both labels

-- kara
Source: StackOverflow

1/16/2021

you can't create replicaset without spec.template.spec.containers field. as this one is by default required to create replica-set in k8s. so you must need to add template field . and you can actually do what you want , just use your pod as here in template spec. template is the actual pod spec with which you are going to create your replica-set's pods.

this one is going to do the exact thing you are asking for:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: user-replicaset
  labels:
    app: user-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-pod
  template:
    metadata:
      labels:
        app: user-pod
    spec:
      containers:
      - name: user-container
        image: kia9372/store-user
-- Emon46
Source: StackOverflow