Assume that Kubernetes has scheduled two pods A and B in a node N. If the resource capacity of the Node N is (30 CPU, 70 Memory) and pod A requests (5 CPU, 8 memory) and pod B requestes (4 CPU, 10 memory), is it possible to share the resources among two pods in a way that we maintain the efficieny of the cluster and maximize the allocation of pods? How can I change the codes to achieve this? Assuming that each pod maintains 1 container.
Kubernetes already does that.
Resource Requests are soft reservations, that means, the scheduler will consider it as a requirement when placing the pod in the node, it will allocate the resource to a POD but won't reserve the resources to be used exclusively by the pod that requested it.
If the POD request 1Gb of memory and consumed only 500Mb, other pods will be able to consume the remainder.
The main issue is when other PODs does not set limits, this will prevent the scheduler of controlling the load properly and other running pods might affect the pod. Other issue is when Limits are set too high and when being consumed will reach the node capacity.
To have a proper balance and efficiency, requests and limits should be set appropriately and prevent over-commitment.
This other SO shows a nice example of it: Allocate or Limit resource for pods in Kubernetes?