I created a pod with kubectl create -f pod.xml and kubectl apply -f pod.xml using the below yaml and I don't see any difference, a pod gets created with both the commands. The K8S document, mentions imperative and declarative commands. But, still the create and apply behave the same way.
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox
command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
What's the difference? Also, how is kubectl apply declarative and kubectl create imperative? Both of them take one or multiple yaml files with the
object details in it.
There is a subtle difference between
kubectl createandkubectl applycommands.The
kubectl createcommand creates a new resource. So, if the command is run again it will throw an error as resource names should be unique in a namespace.2) The
kubectl applycommand applies the configuration to a resource. If the resource is not there then it will be created. Thekubectl applycommand can be run the second time as it simply applies the configuration as shown below. In this case, the configuration hasn't changed. So, the pod hasn't changed.In the
kubectl create, we specify a certain action, in this casecreateand so it is imperative. In thekubectl applycommand we specify the target state of the system and don't specify a certain action and so declarative. We let the system decide what action to take. If the resource is not there it will create it, if the resource is there then it will apply the configuration to the existing resource.From an execution perspective, there is no difference when a resource is created for the first time between
kubectl createandkubectl applyas shown above. But, the second time thekubectl createwill throw an error.It took me some time to get around it, but it makes sense now.