在生产环境中,有时候我们可能要定义多个command,网上搜索了一些感觉还是如下使用ConfigMap的方式最好使用,通过编写一个ConfigMap文件,挂载到pod内部,然后在command字段中直接调用这个configMap脚本文件即可,需要注意的是,这个脚本最后一行运行的命令要在后台运行,否则pod的状态会处于Complete。

apiVersion: v1
kind: ConfigMap
metadata:
  name: http-configmap
  namespace: http
data:
  services.sh: |-
    #!/bin/bash
    sudo service nginx start && ./Daemon -f /data.json&
    sed -i s/127.0.0.1/${MY_POD_IP}/g config.ini
    ./HttpServer
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: http-deployment
  labels:
    k8s-app: http
  namespace: http
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: http
  template:
    metadata:
      labels:
        k8s-app: http
      namespace: http
    spec:
      imagePullSecrets:
      - name: images-docker-rsq
      containers:
      - name: http
        image: images.rsq.com:5000/rsq:test
        imagePullPolicy: IfNotPresent
        workingDir: /data
        volumeMounts:
        - mountPath: /data/services.sh
          name: configmap-volume
          readOnly: true
          subPath: services.sh
        command: ["./services.sh"]
        env:
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        ports:
        - name: daemon
          containerPort: 10086
          protocol: TCP
      nodeSelector:
        role: worker
      volumes:
        - name: configmap-volume
          configMap:
            defaultMode: 0777
            name: http-configmap

还有一种方式就是使用lifecycle的字段,即pod生命周期,可指定pod启动后执行的命令和pod停止前执行的命令。

    lifecycle:
      postStart:
        exec:
          command: ["bash", "/data/sed.sh"]
      preStop:
        exec:
          command: ["bash", "echo 'nihao' "]
Logo

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

更多推荐