前面說了init容器initContainers,這主要是為應用容器做前期准備工作的,一般都會用到shell腳本,這就會用到command,這里寫寫command的用法。
command就是將命令在創建的容器中執行,有這些命令去完成一些工作,command用法和dockerfile中的cmd差不多, command可以單獨寫,也可以分成command和參數args,可以參考之前的CMD去理解,例如下面的寫法都可以。
command: ['/bin/sh'] command: ["rm", "-fr", "/var/lib/dbs/lost+found"] command: - 'sh' - '-c' - 'DATA_SOURCE_NAME="root@(localhost:3306)/" /bin/mysqld_exporter' command: ["sh", "-c", "until nslookup myservice; do echo waiting for myservice; sleep 2; done;"] command: ["sh"] args: ["-c","until nslookup myservice; do echo waiting for myservice; sleep 2; done;"] livenessProbe: exec: command: - /bin/sh - -c - 'wget -O - -q --header "Authorization: Basic `echo -n \"$RABBIT_MANAGEMENT_USER:$RABBIT_MANAGEMENT_PASSWORD\" | base64`" http://localhost:15672/api/healthchecks/node | grep -qF "{\"status\":\"ok\"}"' initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }} periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
另外args還有一種寫法,可以理解成args后面是一個.sh文件,command來直接執行一個腳本文件,可以寫相對復雜的腳本。
command: ['sh'] args: - "-c" - | set -ex if [ ! -d "/opt/ShenTong/odbs/OSRDB" ];then mkdir /opt/ShenTong/odbs/ cp -r /opt/OSRDB /opt/ShenTong/odbs/ else echo "數據庫文件已存在" fi
最后貼一個官方寫的一個rabbitmq的完整例子
spec: {{- if .Values.image.pullSecrets }} imagePullSecrets: {{- range .Values.image.pullSecrets }} - name: {{ . }} {{- end }} {{- end }} terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }} securityContext: {{ toYaml .Values.securityContext | indent 10 }} serviceAccountName: {{ template "rabbitmq-ha.serviceAccountName" . }} initContainers: - name: bootstrap image: {{ .Values.registry }}{{ .Values.busyboxImage.repository}}{{ .Values.arch }}:{{ .Values.busyboxImage.tag}} imagePullPolicy: {{ .Values.busyboxImage.pullPolicy }} command: ['sh'] args: - "-c" - | set -ex cp /configmap/* /etc/rabbitmq rm -f /var/lib/rabbitmq/.erlang.cookie {{- if .Values.forceBoot }} if [ -d "${RABBITMQ_MNESIA_DIR}" ]; then touch "${RABBITMQ_MNESIA_DIR}/force_load" fi {{- end }} env: - name: POD_NAME valueFrom: fieldRef: apiVersion: v1 fieldPath: metadata.name - name: RABBITMQ_MNESIA_DIR value: /var/lib/rabbitmq/mnesia/rabbit@$(POD_NAME).{{ template "rabbitmq-ha.fullname" . }}-discovery.{{ .Release.Namespace }}.svc.{{ .Values.clusterDomain }} resources: {{ toYaml .Values.initContainer.resources | indent 12 }} volumeMounts: - name: configmap mountPath: /configmap - name: config mountPath: /etc/rabbitmq - name: {{ .Values.persistence.name }} mountPath: /var/lib/rabbitmq