Linux通过curl访问docker.sock/API执行docker操作

来自三线的随记
Admin讨论 | 贡献2023年5月5日 (五) 20:02的版本

官方API doc: https://docs.docker.com/engine/api/v1.41/

官方API doc(with example): https://docs.docker.com/engine/api/sdk/examples/

不同版本的docker的api doc: https://docs.docker.com/engine/api/#api-version-matrix

tips: Linux下对socket进行抓包

通过curl socket完成镜像拉取操作

基本报文

POST /v1.41/images/create?fromImage=10.82.123.123%2Fpublic%2Fmaven&tag=3.3.9-public HTTP/1.1
Host: docker
User-Agent: Docker-Client/20.10.17 (linux)
Content-Length: 0
Content-Type: text/plain

命令实现

curl --unix-socket /var/run/docker.sock "http://localhost/v1.41/images/create?fromImage=10.82.123.123%2Fpublic%2Fmaven&tag=3.3.9-public" -X POST

如果拉取镜像需要认证可以加上http header

X-Registry-Auth: eyJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiJwYXNzd29yZCIsInNlcnZlcmFkZHJlc3MiOiIxMC44Mi4xMjMuMTIzIn0=

一个简单的通过socket进行清理dangling镜像的例子

#!/bin/env bash
docker_api_version=v1.41
curl_options=(
  "-s"
  "--unix-socket" "/var/run/docker.sock"
)
dangling_images=(`curl "${curl_options[@]}" "http://localhost/${docker_api_version}/images/json?filters=%7B%22dangling%22%3A%5B%22true%22%5D%7D&all=1" | jq -r .[].Id`)

echo "cleaning dangline images:"
for image in ${dangling_images[*]}
do
  echo $image
  (set -x; curl -X DELETE "${curl_options[@]}" "http://localhost/${docker_api_version}/images/$image" )
done