Keep a docker container running and not exiting

In the kubernetes environment, we can keep a container(pod) alive and avoid it exits immediately after starting.

Method one

1.
Use a long-time-run command in Dockerfile

CMD ["sh", "-c", "tail -f /dev/null"]

or

CMD ["sh", "-c", "sleep infinity"]

2.
Build the docker image and push to docker repository

3.
Launch the container

$ kubectl run mycontainer -it --image=<docker-image-name>

Method two

When to deploy an application with kubernetes statefulset, we also can add it to the statefulset yaml file instead of adding it to the docker image through Dockerfile.

$ cat myapp.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: myapp
spec:
  serviceName: myapp
  replicas: 1
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: noname/myapp:latest
        command: ["sh", "-c", "tail -f /dev/null"]
        imagePullPolicy: Always
        volumeMounts:
        - name: myapp-data
          mountPath: /data
        - name: myapp-log
          mountPath: /log
        securityContext:
          privileged: true
  volumeClaimTemplates:
  - metadata:
      name: myapp-data
    spec:
      storageClassName: <storage-class>
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 20Gi
  - metadata:
      name: myapp-log
    spec:
      storageClassName: <storage-class>
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 1Gi

$ kubectl apply -f myapp.yaml