Docker API v1.40获取容器日志遇400错误:如何正确调用接口?
Hey there! That 400 error you're hitting is a common gotcha with the Docker logs API—while the docs list the main status codes, they don't explicitly highlight this required parameter check. Let's break down how to fix it and properly fetch container logs.
Why You're Getting the 400 Error
The /containers/{id}/logs endpoint requires you to specify at least one log stream you want to retrieve: either the container's standard output (stdout) or standard error (stderr). If you skip both parameters, Docker has no idea which logs to send back, hence the "Bad parameters" message.
Correct Request Format
To make a valid request, add either stdout=true or stderr=true (or both) as query parameters. Here's a breakdown of key parameters you'll use:
stdout=true: Fetch logs from the container's standard output streamstderr=true: Fetch logs from the container's standard error stream- Optional extras:
follow=true: Keep the connection open to stream new logs in real-timetail=N: Only retrieve the lastNlines of logs (replaceNwith a number, or useallfor all logs)timestamps=true: Include timestamps with each log line
Example Requests
Basic Request (Fetch Both stdout and stderr)
Using curl to get the last 20 lines of both streams:
curl -X GET "http://localhost:2375/containers/your-container-id/logs?stdout=true&stderr=true&tail=20"
Real-Time Log Streaming
To follow logs as they're generated:
curl -X GET "http://localhost:2375/containers/your-container-id/logs?stdout=true&stderr=true&follow=true×tamps=true"
Additional Notes
- Make sure your Docker daemon is configured to allow API access (by default, it listens on
unix:///var/run/docker.sock; if using TCP, ensure it's enabled securely) - If you get a 404 error, double-check that the container ID is correct and the container exists
- For authenticated API access, include your auth token in the request headers (e.g.,
Authorization: Bearer your-token)
内容的提问来源于stack exchange,提问作者Capan

