本地环境变量无法传递至VS Code开发容器问题排查
本地环境变量无法传递至VS Code Docker Compose开发容器
使用Docker Compose配置的VS Code开发容器启动时,本地机器设置的目标环境变量无法传递到容器内,尽管docker-compose.yml和devcontainer.json均已配置允许传递本地环境变量。
相关文件
devcontainer.json
{ "remoteEnv": { "MYVAR": "${localEnv:MYVAR}" }, "containerEnv": { "MYVAR": "${localEnv:MYVAR}" }, "customizations": { "vscode": { "extensions": [ "ms-python.python", "ms-python.vscode-pylance" ], "settings": { "#terminal.integrated.defaultProfile.linux#": "/bin/bash", "python.defaultInterpreterPath": "/usr/local/bin/python", "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", "python.formatting.blackPath": "/usr/local/py-utils/bin/black", "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", "python.linting.enabled": true, "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", "python.linting.pylintEnabled": true, "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint" } } }, "dockerComposeFile": "docker-compose.yml", "features": { "ghcr.io/devcontainers/features/docker-from-docker:1": { "version": "latest" }, "ghcr.io/devcontainers/features/github-cli:1": { "version": "latest" } }, "name": "Development", "service": "dev", "shutdownAction": "stopCompose", "workspaceFolder": "/workspace" }
docker-compose.yml
(已移除其他服务以简化内容)
version: '3.8' services: dev: image: python:3.9-slim-buster container_name: dev volumes: - /usr/bin/docker:/usr/bin/docker - /var/run/docker.sock:/var/run/docker.sock - ../:/workspace entrypoint: [/bin/bash, ./.devcontainer/entrypoint.sh] command: sleep infinity environment: - MYVAR=${MYVAR} networks: custom_network: networks: custom_network: name: custom_network driver: bridge ipam: driver: default
entrypoint.sh
(仅保留相关代码)
#!/bin/bash exec "$@"
操作步骤
- 在本地VS Code终端执行
export MYVAR=foo导出环境变量 - 运行VS Code扩展命令:
Dev Containers: Rebuild and Reopen in Container - 在开发容器的shell中执行
echo $MYVAR,结果为空
已尝试方案
- 移除devcontainer.json中的
remoteEnv和containerEnv配置,问题未解决 - 按照VS Code官方文档要求,已勾选「终端 > 集成:继承环境变量」选项
- 操作前删除已停止的开发容器,结果依旧
内容的提问来源于stack exchange,提问作者Marshallm
相关产品推荐
相关产品推荐

