1、问题

pod启动或者通过ReplicaSet等控制器启动pod后,pod的状态一瞬间呈现Completed状态,随后一直显示CrashLoopBackOff状态,导致pod一直重启失败,如下所示

[root@k8s-master01 sc_work]# kubectl create -f replica_set_example.yaml 
replicaset.extensions/nginx-relica created
[root@k8s-master01 sc_work]# kubectl get pod
NAME                 READY   STATUS      RESTARTS   AGE
nginx-relica-d6fhn   0/1     Completed   0          3s
nginx-relica-gqsbn   0/1     Completed   0          3s
nginx-relica-nvjk5   0/1     Completed   1          3s
[root@k8s-master01 sc_work]# kubectl get pod
NAME                 READY   STATUS             RESTARTS   AGE
nginx-relica-d6fhn   0/1     CrashLoopBackOff   1          6s
nginx-relica-gqsbn   0/1     CrashLoopBackOff   1          6s
nginx-relica-nvjk5   0/1     CrashLoopBackOff   1          6s

所用的yaml如下所示:

apiVersion: extensions/v1beta1
kind: ReplicaSet
metadata:
  name: nginx-relica
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx-label
  template:
    metadata:
      labels:
        app: nginx-label
    spec:
      containers:
      - name: nginx-pod
        image: nginx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        command: ["/bin/sh", "-c", "echo hello world > /usr/share/nginx/html/hello.html"]

2、原因

当ReplicaSet控制创建3个pod后,3个pod中分别启动了容器nginx-pod,启动容器后,以非常短的时间执行 ["/bin/sh", “-c”, “echo hello world > /usr/share/nginx/html/hello.html”]后,容器就要结束了,退出码为0,pod状态为completed状态。但ReplicaSet设置的副本数为3,导致3个pod要重启,但pod中容器只执行一个command命令就结束,导致pod的生命周期非常短,k8s都来不及启动就消亡了,导致pod出现CrashLoopBackOff状态。

3、解决办法

延长pod的声明周期,比如yaml改成如下形式,在command中增加sleep延长pod的运行时间。

apiVersion: extensions/v1beta1
kind: ReplicaSet
metadata:
  name: nginx-relica
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx-label
  template:
    metadata:
      labels:
        app: nginx-label
    spec:
      containers:
      - name: nginx-pod
        image: nginx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        #command中增加sleep,延长pod运行时间
        command: ["/bin/sh", "-c", "echo hello world > /usr/share/nginx/html/hello.html; sleep 60"]

删除原来的ReplicaSet后,再重新执行ReplicaSet,pod正常运行

[root@k8s-master01 sc_work]# kubectl create -f replica_set_example.yaml 
replicaset.extensions/nginx-relica created
[root@k8s-master01 sc_work]# kubectl get pod
NAME                 READY   STATUS    RESTARTS   AGE
nginx-relica-4vjl9   1/1     Running   0          4s
nginx-relica-5l7w2   1/1     Running   0          4s
nginx-relica-t6qdc   1/1     Running   0          4s
[root@k8s-master01 sc_work]# kubectl get pod
NAME                 READY   STATUS    RESTARTS   AGE
nginx-relica-4vjl9   1/1     Running   0          16s
nginx-relica-5l7w2   1/1     Running   0          16s
nginx-relica-t6qdc   1/1     Running   0          16s
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐