9

I see in the Docker Remote API Docs that filter can be used to filter on status but I'm unsure how to form the request:

https://docs.docker.com/reference/api/docker_remote_api_v1.16/#list-containers

GET /containers/json?filters=status[exited] ?????

How should this be formatted to display ONLY exited containers?

Ken J
  • 4,312
  • 12
  • 50
  • 86

3 Answers3

21

jwodder is correct on the filter but I wanted to go through this step by step as I wasn't familiar with the Go data types.

The Docker API documentation refers to using a map[string][]string for a filter, which is a Go map (hash table)

  • map[string] defines a map with keys of type string

  • []string is the type definition for the values in the map. A slice [] is an array without fixed length. Then the slice is made up of string values.

So the API requires a hash map of arrays containing strings. This Go Playground demonstrates marshalling the Go filter data:

mapS := map[string][]string{ "status":[]string{"exited"} }

Into JSON:

{ "status": [ "exited" ] }

So adding that JSON to the Docker API request you get:

GET /containers/json?all=1&filters={%22status%22:[%22exited%22]}

all=1 is included to report exited containers (like -a on the command line).

It might be easier for non Go people if they just documented the JSON structure for the API : /

Community
  • 1
  • 1
Matt
  • 68,711
  • 7
  • 155
  • 158
  • I've tried escaping the quotes in the browser and using curl but both give me no results. How can I get a valid response with this request? – Ken J Jan 20 '15 at 21:49
  • You need to add `all=1` for `exited` to be reported. answer updated – Matt Jan 20 '15 at 21:55
  • Perfect! That's what I was missing. This worked for me: http://localhost:5555/containers/json?all=1&filters={%22status%22:%5B%22exited%22%5D} – Ken J Jan 20 '15 at 22:29
  • Thank you so much for the detailed explanation. – Erik Larsson Oct 26 '16 at 12:28
7

The most elegant way to use docker with curl and don't bother with encoding I found in this answer. Basically, it's tell curl to use data as query parameter and encode it. To get exited container the query may look like:

curl -G -XGET "http://localhost:5555/containers/json" \
    -d 'all=1' \
    --data-urlencode 'filters={"status":["exited"]}' | python -m json.tool
Community
  • 1
  • 1
Anton Bessonov
  • 9,208
  • 3
  • 35
  • 38
5

By my reading of the docs, it should be:

GET /containers/json?filters={"status":["exited"]}

Some of that might need to be URL-encoded, though.

jwodder
  • 54,758
  • 12
  • 108
  • 124
  • What's the correct way to encode the URL? http://localhost:5555/containers/json?filters={%27status%27%3A%5B%27exited%27%5D} isn't working. – Ken J Jan 20 '15 at 21:00
  • curl -X GET http://localhost:5555/containers/json?filters=%7B%22status%22%3A%5B%22exited%22%5D%7D returned [] while curl -X GET http://localhost:5555/containers/json?all=1 returns correctly – Ken J Jan 20 '15 at 21:21