自定义Docker扩展

Docker扩展包括几个Visual Studio Code任务,用于控制Docker 构建运行的行为,并构成调试时容器启动的基础。

任务允许大量的控制和自定义。最终配置是通用默认值、平台特定默认值(如Node.js、Python或.NET)和用户输入的组合。当用户输入与默认值冲突时,用户输入优先。

Docker 扩展任务支持 Visual Studio Code 任务的所有常见功能(例如,将任务分组为复合任务)。有关常见任务功能和属性的更多信息,请参阅 Visual Studio Code 的自定义任务文档。

Docker 构建任务

docker-build 任务使用 Docker 命令行(CLI)构建 Docker 镜像。该任务可以单独使用,也可以作为一系列任务的一部分,用于在 Docker 容器中运行和/或调试应用程序。

docker-build任务最重要的配置设置是dockerBuildplatform

  • dockerBuild 对象指定了 Docker 构建命令的参数。此对象指定的值直接应用于 Docker 构建 CLI 调用。
  • platform 属性是一个提示,用于改变 docker-build 任务确定 Docker 构建默认值的方式。

请参阅属性参考以获取所有任务属性的完整列表。

平台支持

虽然tasks.json中的docker-build任务可以用于构建任何Docker镜像,但该扩展对Node.js、Python和.NET Core有明确的支持(并简化了配置)。

Node.js (docker构建)

使用默认值的最小配置

一个基于Node.js的Docker镜像,如果没有特定的平台选项,只需将platform属性设置为node

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Build Node Image",
      "type": "docker-build",
      "platform": "node"
    }
  ]
}

平台默认值

对于Node.js Docker镜像,docker-build任务推断以下选项:

Property Inferred Value
dockerBuild.context The same directory in which the package.json resides.
dockerBuild.dockerfile The file Dockerfile in the same directory as the package.json resides.
dockerBuild.tag The application's name property in package.json (if defined), else the base name of the folder in which package.json resides.

Python (docker构建)

使用默认值的最小配置

一个基于Python的Docker镜像,如果没有特定的平台选项,可以简单地将platform属性设置为python

{
  "tasks": [
    {
      "type": "docker-build",
      "label": "docker-build",
      "platform": "python"
    }
  ]
}

平台默认值

对于Python Docker镜像,docker-build任务推断以下选项:

Property Inferred Value
dockerBuild.context The default context is the workspace folder.
dockerBuild.dockerfile The default Dockerfile path will be in the root of the workspace folder.
dockerBuild.tag The base name of the root workspace folder.
dockerBuild.pull Defaults to true in order to pull new base images before building.

.NET (docker构建)

使用默认值的最小配置

当你构建一个基于.NET的Docker镜像时,你可以省略platform属性,只需设置netCore对象(当netCore对象存在时,platform隐式设置为netcore)。请注意,appProject是一个必需的属性:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Build Node Image",
      "type": "docker-build",
      "netCore": {
        "appProject": "${workspaceFolder}/project.csproj"
      }
    }
  ]
}

平台默认值

对于基于.NET的镜像,docker-build任务推断以下选项:

Property Inferred Value
dockerBuild.context The root workspace folder.
dockerBuild.dockerfile The file Dockerfile in the root workspace folder.
dockerBuild.tag The base name of the root workspace folder.

构建任务参考

以下是可用于配置docker-build任务的所有属性。除非另有说明,否则所有属性都是可选的。

Property Description
dockerBuild Options for controlling the docker build command executed (see below).
Required unless platform is set.
platform Determines the platform: .NET (netcore) or Node.js (node) and default settings for docker build command.
node Determines options specific for Node.js projects (see below).
python There are no object properties for Python in the docker-build task.
netCore Determines options specific for .NET projects (see below).

dockerBuild 对象属性

Property Description docker build CLI Equivalent
context The path to the Docker build context.
Required, unless inferred from the platform.
PATH
dockerfile The path to the Dockerfile.
Required, unless inferred from the platform.
-f or --file
tag The tag applied to the Docker image.
Required, unless inferred from the platform.
-t or --tag
buildArgs Build arguments applied to the command line. This is a list of key-value pairs. --build-arg
labels Labels added to the Docker image. This is a list of key-value pairs (a JSON object).
In addition to labels specified here, a label com.microsoft.created-by, set to visual-studio-code is added to the image. This behavior can be turned off by setting includeDefaults property of the labels object to false.
--label
target The target in the Dockerfile to build to. --target
pull Whether or not to pull new base images before building. --pull
customOptions Any extra parameters to add before the context argument. No attempt is made to resolve conflicts with other options or validate this option. (any)

节点对象属性 (docker-build 任务)

Property Description Default
package The path to the package.json file associated with the Dockerfile and docker-build task. The file package.json in the root workspace folder.

netCore 对象属性 (docker-build 任务)

Property Description
appProject The .NET project file (.csproj, .fsproj, etc.) associated with the Dockerfile and docker-build task.
Required always.

Docker 运行任务

tasks.json 中的 docker-run 任务使用 Docker 命令行 (CLI) 创建并启动一个 Docker 容器。该任务可以单独使用,也可以作为任务链的一部分,用于在 Docker 容器内调试应用程序。

docker-run 任务最重要的配置设置是 dockerRunplatform

  • dockerRun 对象指定了 Docker 运行命令的参数。此对象指定的值直接应用于 Docker 运行 CLI 调用。
  • platform 属性是一个提示,用于改变 docker-run 任务确定 Docker 运行默认值的方式。

请参阅属性参考以获取所有任务属性的完整列表。

Docker 运行平台支持

虽然docker-run任务可以用于运行任何Docker镜像,但该扩展对Node.js、Python和.NET有明确的支持(并简化了配置)。

Node.js (docker-run)

使用默认值的最小配置

一个基于Node.js的Docker镜像,如果没有特定的平台选项,只需将platform属性设置为node

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run Node Image",
      "node": "docker-run",
      "platform": "node"
    }
  ]
}

平台默认值

对于基于Node.js的Docker镜像,docker-run任务推断以下选项:

Property Inferred Value
dockerRun.command Generated from the npm start script in the package.json (if it exists), else generated from the main property in the package.json.
dockerRun.containerName Derived from the application package name.
dockerRun.image The tag from a dependent docker-build task (if one exists) or derived from the application package name, itself derived from the name property within package.json or the base name of the folder in which it resides.

Python (docker-run)

在构建基于Python的Docker镜像时,您可以省略platform属性,只需设置python对象(当存在python对象时,platform会隐式设置为python

Django 应用的最小配置

{
  "type": "docker-run",
  "label": "docker-run: debug",
  "dependsOn": ["docker-build"],
  "python": {
    "args": ["runserver", "0.0.0.0:8000", "--nothreading", "--noreload"],
    "file": "path_to/manage.py"
  }
}

Flask 应用程序的最小配置

{
  "type": "docker-run",
  "label": "docker-run: debug",
  "dependsOn": ["docker-build"],
  "dockerRun": {
    "env": {
      "FLASK_APP": "path_to/flask_entry_point.py"
    }
  },
  "python": {
    "args": ["run", "--no-debugger", "--no-reload", "--host", "0.0.0.0", "--port", "5000"],
    "module": "flask"
  }
}

通用应用程序的最小配置

{
  "type": "docker-run",
  "label": "docker-run: debug",
  "dependsOn": ["docker-build"],
  "python": {
    "file": "path_to/app_entry_point.py"
  }
}

平台默认值

对于基于Python的Docker镜像,docker-run任务推断以下选项:

Property Inferred Value
dockerRun.command Generated by the Python object and is called by the Python Debugger.
dockerRun.containerName Derived from the base name of the root workspace folder.
dockerRun.image The tag from a dependent docker-build task (if one exists) or derived from the base name of the root workspace folder.

.NET (docker-run)

使用默认值的最小配置

在构建基于 .NET 的 Docker 镜像时,您可以省略 platform 属性,只需设置 netCore 对象(当存在 netCore 对象时,platform 隐式设置为 netcore)。请注意,appProject 是一个必需的属性:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run .NET Core Image",
      "type": "docker-run",
      "netCore": {
        "appProject": "${workspaceFolder}/project.csproj"
      }
    }
  ]
}

平台默认值

对于基于.NET的镜像,docker-run任务推断以下选项:

Property Inferred Value
dockerRun.containerName Derived from the base name of the root workspace folder.
dockerRun.env Adds the following environment variables as required: ASPNETCORE_ENVIRONMENT, ASPNETCORE_URLS, and DOTNET_USE_POLLING_FILE_WATCHER.
dockerRun.image The tag from a dependent docker-build task (if one exists) or derived from the base name of the root workspace folder.
dockerRun.os Linux
dockerRun.volumes Adds the following volumes as required: the local application folder, the source folder, the debugger folder, the NuGet package folder, and NuGet fallback folder.

运行任务参考

以下是可用于配置docker-run任务的所有属性。除非另有说明,否则所有属性都是可选的。

Property Description
dockerRun Options for controlling the docker run command executed (see below).
Required unless platform is set.
platform Determines the platform: .NET (netcore) or Node.js (node) and default settings for docker run command.
node For Node.js projects, this controls various options (see below).
python For Python projects, this controls various options (see below).
netCore For .NET projects, this controls various options (see below).

dockerRun 对象属性

Property Description CLI Equivalent
image The name (tag) of the image to run.
Required unless inferred from the platform.
IMAGE
command The command to run upon starting the container.
Required, unless inferred from the platform.
COMMAND [ARG...]
containerName The name given to the started container.
Required, unless inferred from the platform.
--name
env Environment variables set in the container. This is a list of key-value pairs. -e or --env
envFiles This is a list of .env files. --env-file
labels Labels given to the started container. This is a list of key-value pairs. --label
network The name of the network to which the container will be connected. --network
networkAlias The network-scoped alias for the started container. --network-alias
os Default is Linux, the other option is Windows. The container operating system used. N/A
ports The ports to publish (map) from container to host. This is a list of objects (see below). -p or --publish
portsPublishAll Whether to publish all ports exposed by the Docker image. Defaults to true if no ports are explicitly published. -P
extraHosts The hosts to add to the container for DNS resolution. This is a list of objects (see below). --add-host
volumes The volumes to map into the started container. This is a list of objects (see below). -v or --volume
remove Whether or not to remove the container after it stops. --rm
customOptions Any extra parameters to add before the image argument. No attempt is made to resolve conflicts with other options or validate this option. (any)

端口对象属性

Property Description Default
containerPort The port number bound on the container.
Required.
hostPort The port number bound on the host. (randomly selected by Docker)
protocol The protocol for the binding (tcp or udp). tcp

extraHosts 对象属性

Property Description
hostname The hostname for DNS resolution.
Required.
ip The IP address associated with the above hostname.
Required.

volumes 对象属性

Property Description Default
localPath The path on the local machine that will be mapped.
Required.
containerPath The path in the container to which the local path will be mapped.
Required.
permissions Permissions the container has on the mapped path. Can be ro (read-only) or rw (read-write). Container dependent.

节点对象属性 (docker-run 任务)

Property Description Default
package The path to the package.json file associated with the docker-run task. The file package.json in the root workspace folder.
enableDebugging Whether or not to enable debugging within the container. false
inspectMode Defines the initial interaction between the application and the debugger (default or break).
The value default allows the application to run until the debugger attaches.
The value break prevents the application from running until the debugger attaches.
default
inspectPort The port on which debugging should occur. 9229

python 对象属性 (docker-run 任务)

Property Description Default
args Arguments passed to the Python app. Platform dependent. Defaults of scaffolding shown above
debugPort The port that the debugger will listen on. 5678
wait Whether to wait for debugger to attach. true
module The Python module to run (only module or file should be chosen).
file The Python file to run (only module or file should be chosen).

netCore 对象属性 (docker-run 任务)

Property Description
appProject The .NET project file (.csproj, .fsproj, etc.) associated with docker-run task.
Required.
configureSsl Whether to configure ASP.NET Core SSL certificates and other settings to enable SSL on the service in the container.
enableDebugging Whether to enable the started container for debugging. This will infer additional volume mappings and other options necessary for debugging.

Docker Compose 任务

tasks.json 中的 docker-compose 任务使用 Docker Compose 命令行 (CLI) 创建并启动 Docker 容器。该任务可以单独使用,也可以作为任务链的一部分,用于在 Docker 容器内调试应用程序。

docker-compose任务最重要的配置设置是dockerCompose

  • dockerCompose 对象指定了 Docker Compose 命令的参数。此对象指定的值直接应用于 Docker Compose CLI 调用。

请参阅属性参考以获取所有任务属性的完整列表。

示例配置

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run docker-compose up",
      "type": "docker-compose",
      "dockerCompose": {
        "up": {
          "detached": true,
          "build": true,
          "services": ["myservice"]
        },
        "files": [
          "${workspaceFolder}/docker-compose.yml",
          "${workspaceFolder}/docker-compose.debug.yml"
        ]
      }
    }
  ]
}

Compose 任务参考

以下是可用于配置docker-compose任务的所有属性。除非另有说明,否则所有属性都是可选的。

Property Description
dockerCompose Options for controlling the docker-compose command executed (see below).
Required.

dockerCompose 对象属性

Property Description CLI Equivalent
up Run a docker-compose up command.
Either this or down must be specified, but not both.
docker-compose up
down Run a docker-compose down command.
Either this or up must be specified, but not both.
docker-compose down
files The list of Docker Compose YAML files to use in the docker-compose command. If not specified, the Docker Compose CLI looks for docker-compose.yml and docker-compose.override.yml. -f <file>
envFile File of environment variables read in and applied to the containers. --env-file <file>
projectName Alternate project name to use when naming and labeling Docker objects. If using an alternate project name when composing up, the same project name must be specified when composing down. --project-name <name>

up 对象属性

Property Description CLI Equivalent Default
detached Whether or not to run detached. -d true
build Whether or not to build before running. --build true
scale Number of instances of each service to run. This is a list of key-value pairs. --scale SERVICE=NUM
services A subset of the services to start. Cannot be combined with profiles. [SERVICE...] (all)
profiles A subset of the profiles to start. Cannot be combined with services. --profile <profile> (all)
customOptions Any extra parameters to add after the up argument. No attempt is made to resolve conflicts with other options or validate this option. (any)

down 对象属性

Property Description CLI Equivalent Default
removeImages Whether to remove images, and which. all will remove all images used by any service, local will remove only images without a custom tag. Leaving this unset will remove no images. --rmi
removeVolumes Whether or not to remove named volumes. -v false
customOptions Any extra parameters to add after the down argument. No attempt is made to resolve conflicts with other options or validate this option. (any)

命令自定义

Docker扩展在执行各种操作时会执行一系列Docker CLI命令,例如构建镜像、运行容器、附加到容器以及查看容器日志。其中一些命令具有大量可选参数,通常用于非常特定的场景。作为上述Visual Studio Code任务的替代方案,当任务未使用时,可以自定义多个命令。

例如,Compose Up 命令中的 ${serviceList}${profileList} 标记允许轻松启动 Docker Compose YAML 文件中的服务子集。

对于这些可定制的Docker命令,每个命令都有一个配置设置,用于设置要执行的模板。或者,您可以定义多个模板,可以选择使用正则表达式,当匹配时,提示应使用模板的上下文。这些模板支持一些类似于launch.jsontasks.json的令牌,例如${workspaceFolder}

设置 JSON 模式

您有两种配置每个模板的选项(如下所列)。第一个选项是覆盖默认行为的单个模板:

{
  "docker.commands.build": "docker build --rm -f \"${dockerfile}\" -t ${tag} \"${context}\""
}

第二个选项是根据match正则表达式以及用户输入选择的多个模板。

例如,以下示例中展示了三个模板:

{
  "docker.commands.build": [
    {
      "label": "Default build command",
      "template": "docker build --rm -f \"${dockerfile}\" -t ${tag} \"${context}\""
    },
    {
      "label": "Alpine-specific build command",
      "template": "docker build -p 1234:1234 -f \"${dockerfile}\" -t ${tag} \"${context}\"",
      "match": "alpine"
    }
  ]
}

选择行为

选择的命令模板基于以下规则执行:

  1. 如果未配置任何设置,则选择默认命令模板。
  2. 如果只配置了一个模板(如上第一个示例),则选择该模板。
  3. 如果配置了多个模板:
    1. 检查受约束的模板。受约束的模板具有matchmatch正则表达式与上下文提示进行比较——例如,图像名称、容器名称等。
    2. 如果有多个受约束的模板适用,将提示用户选择。如果只有一个适用,则不会提示用户。
    3. 如果没有适用的受约束模板,则检查不受约束的模板。不受约束的模板没有match,因此始终适用。
    4. 如果有多个不受约束的模板适用,将提示用户选择。如果只有一个适用,则不会提示用户。

Docker 构建

Configuration Setting Default Value
docker.commands.build ${containerCommand} build --rm -f "${dockerfile}" -t ${tag} "${context}"

支持的令牌:

Token Description
${containerCommand} The CLI command / executable used to execute container commands.
${dockerfile} The workspace-relative path of the selected Dockerfile.
${tag} The value entered/confirmed by the user upon invoking the build command. If previously built, defaults to the previously entered value for that Dockerfile.
${context} If set, the value of the docker.imageBuildContextPath configuration setting. Otherwise, the workspace-relative folder in which the Dockerfile resides.

注意: 如果 docker.commands.build 设置不包含 ${tag} 标记,用户将 不会 被提示输入/确认标签。

注意match 正则表达式将与选定的 Dockerfile 名称和工作区文件夹名称进行比较。

Docker 运行

Configuration Setting Default Value
docker.commands.run ${containerCommand} run --rm -d ${exposedPorts} ${tag}
docker.commands.runInteractive ${containerCommand} run --rm -it ${exposedPorts} ${tag}

支持的令牌:

Token Description
${containerCommand} The CLI command / executable used to execute container commands.
${exposedPorts} Generated from the list of exposed ports in the image (ultimately from the Dockerfile), where each exposed port is mapped to the same port on the local machine. For example, "EXPOSE 5000 5001" would generate "-p 5000:5000 -p 5001:5001".
${tag} The full tag of the selected image.

注意: match 正则表达式将与所选图像的完整标签进行比较。

Docker 附加

Configuration Setting Default Value
docker.commands.attach ${containerCommand} exec -it ${containerId} ${shellCommand}

支持的令牌:

Token Description
${containerCommand} The CLI command / executable used to execute container commands.
${containerId} The ID of the container to attach to.
${shellCommand} If bash is present in the container, it is substituted here, otherwise sh. In Windows containers, cmd is always used.

注意match 正则表达式将与容器名称和容器镜像的完整标签进行比较。

Docker 日志

Configuration Setting Default Value
docker.commands.logs ${containerCommand} logs -f ${containerId}

支持的令牌:

Token Description
${containerCommand} The CLI command / executable used to execute container commands.
${containerId} The ID of the container to view the logs for.

注意match 正则表达式将与容器名称和容器镜像的完整标签进行比较。

Docker Compose 启动

Configuration Setting Default Value
docker.commands.composeUp ${composeCommand} ${configurationFile} up ${detached} ${build}

支持的令牌:

Token Description
${configurationFile} Set to -f plus the workspace-relative path to the selected Docker Compose YAML file.
${detached} Set to -d if the configuration setting docker.dockerComposeDetached is set to true. Otherwise, set to "".
${build} Set to --build if the configuration setting docker.dockerComposeBuild is set to true. Otherwise, set to "".
${serviceList} If specified, prompts for a subset of the services to start when the command is run.
${profileList} If specified and the Docker Compose YAML file contains profiles, prompts for a subset of the profiles to start when the command is run.
${composeCommand} Set to the value of the docker.composeCommand setting if set, otherwise the extension will try to automatically determine the command to use (docker compose or docker-compose).

Docker Compose 关闭

Configuration Setting Default Value
docker.commands.composeDown ${composeCommand} ${configurationFile} down

支持的令牌:

Token Description
${configurationFile} Set to -f plus the workspace-relative path to the selected Docker Compose YAML file.
${composeCommand} Set to the value of the docker.composeCommand setting if set, otherwise the extension will try to automatically determine the command to use (docker compose or docker-compose).

额外支持的令牌

除了特定命令支持的令牌外,所有命令模板还支持以下令牌:

Token Description
${workspaceFolder} The selected workspace folder path.
${config:some.setting.identifier} The value of any configuration setting, as long as it is a string, number, or boolean. These setting identifiers can be arbitrarily defined and do not need to belong to Visual Studio Code or to any extension.
${env:Name} The value of an environment variable.
${command:commandID} The string return value of a command.