Home Keep a docker container running and not exiting
Post
Cancel

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

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

    or

    1
    
    CMD ["sh", "-c", "sleep infinity"]
    
  2. Build the docker image and push to docker repository

  3. Launch the container

    1
    
    $ 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
$ 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          
This post is licensed under CC BY 4.0 by the author.

Deploy application with kubernetes statefulset

Pull an image from a private docker registry in Kubernetes Pod

Comments powered by Disqus.