Docker - 如何检查容器的卷路径?

Docker - How to Inspect Container for Volume Path?

所以从文档中,我可以查询我的容器的卷:

docker inspect --format="{{.Volumes}}" container

此 returns 格式的路径:

map[/container/path/1:/host/path/1 /container/path/2:/host/path/2]

我的问题是,如何从返回的数据中提取单一路径?假设我只想要 /host/path/2,这样我就可以在脚本中使用它来备份该卷中的数据。

--format 的参数是一个标准的 go text/template 表达式。如果你想获取特定容器路径对应的主机路径,你可以这样做:

$ docker inspect -f '{{index .Volumes "/container/path/1"}}' container
/host/path/1

如果您想生成 host:container 对的列表,您可以这样做:

$ docker inspect -f '{{range $key, $value := .Volumes}}{{printf "%s:%s\n" $key $value}}{{end}}'

哪个会让你:

/container/path/1:/host/path/1
/container/path/2:/host/path/2

在这个例子中,我们利用了这个语法:

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

$variable := pipeline

where $variable is the name of the variable. An action that declares a variable produces no output.

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses.