How to kill a docker container when it reaches set of memory usage or CPU limit

6/15/2019

I have a docker container which running in a pod where I need to restart the pod / container when it exceeds memory usage or CPU limit. How to configure it in docker file

-- user2980608
docker
kubernetes

1 Answer

6/15/2019

CPU and memory limits cannot be given when building a docker and it cannot be configured in Docker File. It is a scheduling problem. You could run your docker with docker run command with different flags to control resources. See Docker Official Document for those control flags for docker run.

As your question is tagged with kubernetes, there is kubernetes way to limit your resources. You would want to add resources in specs for those deployment or pod yaml. For example:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: your_deployment
  labels:
    app: your_app
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: your_app
    spec:
      containers:
      - name: your_container
        image: your_image
        resources:
          limits:
            cpu: "500m"
            memory: "128Mi"
          requests:
            cpu: "250m"
            memory: "64Mi"
        ...

requests affects how docker pod is scheduled on nodes. Memory limit determines when the docker will be killed for OOM and cpu limit determines how the container cpu usage will be throttled (The pod will not be killed).

Meaning of cpu is different for each cloud service providers. For more information, please refer to manage compute resources for Kubernetes

-- Fei
Source: StackOverflow