首页 > 解决方案 > 访问 cron 作业 kubernetes 中的日志

问题描述

我在 kubernetes 中运行 cron 作业,作业成功完成,我将输出记录到内部的日志文件(路径:storage/logs),但由于容器已完成,我无法访问该文件这是我的工作 yaml。

apiVersion: v1
items:
- apiVersion: batch/v1beta1
  kind: CronJob
  metadata:
    labels:
      chart: cronjobs-0.1.0
    name: cron-cronjob1
    namespace: default
  spec:
    concurrencyPolicy: Forbid
    failedJobsHistoryLimit: 1
    jobTemplate:      
      spec:
        template:
          metadata:          
            labels:
              app: cron
              cron: cronjob1
          spec:
            containers:
            - args:
              - /usr/local/bin/php
              - -c
              - /var/www/html/artisan bulk:import
              env:
              - name: DB_CONNECTION
                value: postgres
              - name: DB_HOST
                value: postgres
              - name: DB_PORT
                value: "5432"
              - name: DB_DATABASE
                value: xxx
              - name: DB_USERNAME
                value: xxx
              - name: DB_PASSWORD
                value: xxxx
              - name: APP_KEY
                value: xxxxx
              image: registry.xxxxx.com/xxxx:2ecb785-e927977
              imagePullPolicy: IfNotPresent
              name: cronjob1
              ports:
              - containerPort: 80
                name: http
                protocol: TCP              
            imagePullSecrets:
            - name: xxxxx
            restartPolicy: OnFailure          
            terminationGracePeriodSeconds: 30
    schedule: '* * * * *'
    successfulJobsHistoryLimit: 3

无论如何我可以在 kubectl log 命令或其他替代方法上显示我的日志文件内容吗?

标签: kuberneteskubernetes-cronjob

解决方案


Cronjob根据spec.schedule. 任务完成后 pod 的状态会被设置为completed,但cronjob控制器不会在完成后删除 pod。并且日志文件内容仍然存在于 pod 的容器文件系统中。所以你需要这样做:

# here  you can get the pod_name from the stdout of the cmd `kubectl get pods`
$ kubectl logs -f -n default <pod_name>

推荐阅读