visual-studio-codedocker-composeenvironment-variablesvscode-devcontainer

How to pass variables accessible from VsCode devcontainer.json to docker-compose.yml


In devcontainer.json we have access to these variables:

${localWorkspaceFolder}
${containerWorkspaceFolder}
${localWorkspaceFolderBasename}
${containerWorkspaceFolderBasename}

I have tried making these variables available in .devcontainer.json like this:

{
    "dockerComposeFile": "docker-compose.yml",
    "service": "my-devcontainer",
    "containerEnv": {
          "THING_I_WANT_TO_PASS": "${localWorkspaceFolderBasename}",
      },
      "remoteEnv": {
          "THING_I_WANT_TO_PASS": "${localWorkspaceFolderBasename}",
      },
}

So that they can be used in my docker-compose.yml like so:

services:
  my-devcontainer:
    container_name: "${THING_I_WANT_TO_PASS}-just-example"

But I still get this error VsCode attempts to build the container:

level=warning msg="The "THING_I_WANT_TO_PASS" variable is not set. Defaulting to a blank string.

Solution

  • It's not great, but you can create an .env file during initializeCommand that will be used by docker-compose.yml.

    In .devcontainer.json:

    {
        "dockerComposeFile": "docker-compose.yml",
        "service": "my-devcontainer",
        "initializeCommand": "echo THING_I_WANT_TO_PASS=${localWorkspaceFolderBasename} > .devcontainer/.env"
    }