vscode dev 容器环境变量未暴露给 docker-compose

vscode dev container environment variables not exposing to docker-compose

我的docker-compose.yml看起来像这样

version: "3.8"
services: 
  vscode:
    volumes:
      - ..:/workspace:cached
      - $SSH_AUTH_SOCK:/ssh-agent
      - /var/run/docker.sock:/var/run/docker.sock
    environment: 
      - SSH_AUTH_SOCK=/ssh-agent

问题是 vscode 不想提供任何一种可能性来做 docker-compose run --env ... 的等价物,因此我只剩下

WARNING: The SSH_AUTH_SOCK variable is not set. Defaulting to a blank string.

有什么方法可以让我在不使用 .env 文件或类似文件的情况下将我的变量从我的主机公开到开发容器?

根据 documentation

通过容器从主机公开环境变量

You can pass environment variables from your shell straight through to a service’s containers with the ‘environment’ key by not giving them a value, just like with docker run -e VARIABLE ...:

web:
 environment:
   - DEBUG

The value of the DEBUG variable in the container is taken from the value for the same variable in the shell in which Compose is run.

具体 SSH_AUTH_SOCK 你应该看看

例子

Right, problem is that environment variables are not being exposed properly even with doing that.

使用变量的简单服务 DEBUG

services:
  test:
    image: busybox
    command: ["echo", "${DEBUG}"]
    environment:
      - DEBUG

在不导出变量的情况下使用它,它不起作用并在输出中显示警告。

# running the service
docker-compose up

# WARNING: The DEBUG variable is not set. Defaulting to a blank string.
# Starting d-compose-env_test_1 ... done
# Attaching to d-compose-env_test_1
# test_1  | 
# d-compose-env_test_1 exited with code 0

现在在 运行 之前在主机上导出变量,它起作用了,打印了变量的值。

# exporting the variable
export DEBUG=test
# running the service
docker-compose up

# Recreating d-compose-env_test_1 ... done
# Attaching to d-compose-env_test_1
# test_1  | test
# d-compose-env_test_1 exited with code 0

我昨天在 github 上开了一个问题。结果是 如果你使用 WSL,那么你需要通过你的 ~/.profile 或 ~/.bash_profile.

导出这个变量

We are using a non-interactive login shell to probe the environment variables in WSL and use these as the "local" variables.

https://github.com/microsoft/vscode-remote-release/issues/5806

我刚刚遇到了类似的问题,所以这可能会有所帮助。

我会运行以下内容:

export VARIABLE=VALUE
sudo docker-compose up

问题是我以我的用户身份导出环境变量,然后 运行ning docker-compose 作为 sudo,所以它不会有相同的环境变量。

这可以通过将自己添加到 docker 组来解决,这样您就可以 运行 而无需 sudo

或将变量导出为根(不推荐)