Docker
Docker 物件
▸ listContainers(options?
): Promise
<unknown
>
用於取得容器清單
const containers = await ddClient.docker.listContainers();
▸ listImages(options?
): Promise
<unknown
>
用於取得本地容器映像檔清單
const images = await ddClient.docker.listImages();
有關這些方法的詳細資訊,請參閱 Docker API 參考。
已淘汰的 Docker 物件存取方式
以下方法已淘汰,將在未來的版本中移除。請使用上面指定的方法。
const containers = await window.ddClient.listContainers();
const images = await window.ddClient.listImages();
Docker 命令
擴充套件也可以直接執行 docker
命令列。
▸ exec(cmd
, args
): Promise
< ExecResult
>
const result = await ddClient.docker.cli.exec("info", [
"--format",
'"{{ json . }}"',
]);
結果包含已執行命令的標準輸出和標準錯誤
{
"stderr": "...",
"stdout": "..."
}
在此範例中,命令輸出為 JSON。為了方便起見,命令結果物件也具有輕鬆解析它的方法
result.lines(): string[]
會分割輸出行。result.parseJsonObject(): any
會解析格式良好的 json 輸出。result.parseJsonLines(): any[]
會將每個輸出行解析為 json 物件。
▸ exec(cmd
, args
, options
): void
上述命令會將執行 Docker 命令的結果以串流方式輸出。如果您需要將輸出作為串流方式取得,或者命令的輸出過長,這將非常有用。
await ddClient.docker.cli.exec("logs", ["-f", "..."], {
stream: {
onOutput(data) {
if (data.stdout) {
console.error(data.stdout);
} else {
console.log(data.stderr);
}
},
onError(error) {
console.error(error);
},
onClose(exitCode) {
console.log("onClose with exit code " + exitCode);
},
splitOutputLines: true,
},
});
當您關閉 Docker Desktop 中的儀表板或結束擴充套件 UI 時,擴充套件建立的子程序cess 會自動被終止 (SIGTERM
)。如果需要,您也可以使用 exec(streamOptions)
呼叫的結果來終止 (SIGTERM
) 程序。
const logListener = await ddClient.docker.cli.exec("logs", ["-f", "..."], {
stream: {
// ...
},
});
// when done listening to logs or before starting a new one, kill the process
logListener.close();
此 exec(streamOptions)
API 也可用於監聽 docker 事件
await ddClient.docker.cli.exec(
"events",
["--format", "{{ json . }}", "--filter", "container=my-container"],
{
stream: {
onOutput(data) {
if (data.stdout) {
const event = JSON.parse(data.stdout);
console.log(event);
} else {
console.log(data.stderr);
}
},
onClose(exitCode) {
console.log("onClose with exit code " + exitCode);
},
splitOutputLines: true,
},
}
);
注意
您無法使用它在單個
exec()
呼叫中鏈接命令(例如docker kill $(docker ps -q)
或在命令之間使用管道)。您需要為每個命令呼叫
exec()
並解析結果,以便在需要時將參數傳遞給下一個命令。
有關這些方法的詳細資訊,請參閱 Exec API 參考。
已淘汰的 Docker 命令執行方式
此方法已淘汰,將在未來的版本中移除。請使用下方指定的方法。
const output = await window.ddClient.execDockerCmd(
"info",
"--format",
'"{{ json . }}"'
);
window.ddClient.spawnDockerCmd("logs", ["-f", "..."], (data, error) => {
console.log(data.stdout);
});