Advanced Containers
改进磁盘性能
Remote - Containers 扩展默认使用挂载(bind mounts)方式将源码映射到容器内. 虽然在 Windows 和 macOS 中这种方式最简单, 但是在容器内运行 yarn install / npm install 等命令时会产生磁盘读写性能问题. 通过一下方式可以优化该问题.
在容器内clone仓库
使用命令 Remote-Containers: Clone Repository in Container Volume
使用命名卷(targed named volume)
因为 macOS 和 Windows 在VM中运行容器, bind 命令挂载方式共享文件没有直接使用容器内文件系统操作高效. 幸运的是Docker有个 命名卷(named volume) 概念, 可以优化磁盘读写问题.
Dockerfile 或者镜像
下面介绍将 node_modules 目录使用 volume 方式挂载到容器内的文件系统:
使用属性 workspaceMount 告诉 VS Code 源码在哪儿, 然后使用 mounts 属性将子目录 node_modules 挂载到本地volume中, 完整配置如下:
.devcontainer/devcontainer.json
{
  "name": "Node.js Dev",
  "build": {
    "dockerfile": "Dockerfile",
    "context": "."
  },
  "customizations": {
    "vscode": {
      "settings": {
        "terminal.integrated.shell.linux": "/bin/bash"
      },
      "extensions": [
        "dbaeumer.vscode-eslint"
      ]
    }
  },
  "forwardPorts": [
    3000
  ],
  "postCreateCommand": "npm install",
  "workspaceMount": "source=${localWorkspaceFolder}/,target=/workspace,type=bind,consistency=cached",
  "workspaceFolder": "/workspace",
  "mounts": [
    "source=your-volume-name-here,target=${containerWorkspaceFolder}/node_modules,type=volume"
  ]
  // "remoteUser": "node",
  // "postCreateCommand": "chown node node_modules && npm install"
}
注意
mounts命令里的source指的是 volume 名称.
这种方式有两点需要注意:
- 不能在容器内删除目录 node_modules, 否则会容器会断开和volume的连接, 如果需要删除node_modules, 可以删除该目录下的内容(而不是直接删除该目录):rm -rf node_modules/* node_modules/.*
- 你会发现本地会有一个空的 node_modules文件夹, 可以忽略这个.