Search code examples
dockerkubernetescontainersstdoutstderr

Kubernetes - mount container stdout stderr logs


I use "chentex/random-logger" image, which write stdout/stderr to the container. I want to make deployment yaml, which run the chentex's image, and put it's logs in file inside shared volume. Can I do it without modifying the image?

This is the simple deployment of the image:

apiVersion: v1
kind: Deployment
metadata:
  name: random-logger
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: random-logger
    spec:
      containers:
      - name: random-logger
        image: chentex/random-logger:latest

Solution

  • It is best practice to send log message to stdout for applications running in a container. The chentex/random-logger just follows this approach without any option to configure this, but we can bring up a hack like this:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: random-logger
    spec:
      selector:
        matchLabels:
          app: random-logger
      template:
        metadata:
          labels:
            app: random-logger
        spec:
          containers:
          - name: random-logger
            image: chentex/random-logger:latest
            command: ["sh", "-c",  "./entrypoint.sh &> /logfile"]
    

    When requesting the logs from the running pod there is nothing to see:

    $ kubectl logs random-logger-76c6fd98d5-8d5fm
    

    The application logs are written to logfile within the container:

    $ kubectl exec random-logger-76c6fd98d5-8d5fm cat /logfile
    2019-02-28T00:23:23+0000 DEBUG first loop completed.
    2019-02-28T00:23:25+0000 ERROR something happened in this execution.
    2019-02-28T00:23:29+0000 INFO takes the value and converts it to string.
    2019-02-28T00:23:31+0000 WARN variable not in use.
    2019-02-28T00:23:37+0000 INFO takes the value and converts it to string.
    

    Although this is possible, it is in general not advised. See the Kubernetes documentation about Logging Architecture for more background information.