2

I'm trying to retrieve container logs using Docker API.

Open API documentation of Docker states to get the container logs; syntax that should be used is;

/containers/{id}/logs

According to documentation there could be three response statuses; 200, 404 and 500.

You can see the part of the documentation below;

responses:
        200:
          description: |
                  logs returned as a stream in response body.
                  For the stream format, [see the documentation for the attach endpoint](#operation/ContainerAttach).
                  Note that unlike the attach endpoint, the logs endpoint does not upgrade the connection and does not
                  set Content-Type.
          schema:
            type: "string"
            format: "binary"
        404:
          description: "no such container"
          schema:
            $ref: "#/definitions/ErrorResponse"
          examples:
            application/json:
              message: "No such container: c2ada9df5af8"
        500:
          description: "server error"
          schema:
            $ref: "#/definitions/ErrorResponse"

The interesting part for me is when I make a call I get 400 error which doesn't exist in the docs. Response message is like;

{
    "message": "Bad parameters: you must choose at least one stream"
}

How can I get the container logs using Docker API ?

Capan
  • 686
  • 1
  • 14
  • 32

2 Answers2

2

Specify where to return logs from by sending the stdout or stderr query parameters. Example:

curl --unix-socket /var/run/docker.sock http://localhost/containers/containerId/logs?stdout=true
b0gusb
  • 4,283
  • 2
  • 14
  • 33
0

Using Docker API in Python it can be done like that:

import docker
from docker.models.containers import Container

image_id: str = "the_image_id_that_you_get_from_building"
container_object: Container = docker.from_env().containers.run(
    image_id,
    name="that-nice-name",
    detach=True,
)
for log_line in container_object.logs(stream=True):
    print(log_line.decode("utf-8"), end="")

The execution stops on the for loop - printing all the logs as they appear in the container. As soon as the container exits (is terminated for any reason) the execution leaves the for loop.