13

I am using a standalone Go vscode remote container for development and would like to load environment variables into the container from a file.

All examples I can find are using Docker Compose and its env_file option but using Docker Compose seems overkill for a single container. Is there any way I can achieve this without using Docker Compose?

Pero P.
  • 25,813
  • 9
  • 61
  • 85

1 Answers1

18

In the .devcontainer directory of your project add a file that declares your environment variables, in this case .env:

D:.
│   .gitignore
│   README.md
│
├───.devcontainer
│      .env 
│       devcontainer.json
│       Dockerfile
│
└───.vscode
        settings.json

.env:

MY_URL=https://my.com/
MY_SECRET=unicorns

Then in your devcontainer.json you can define runArgs that pass the .env file as an env-file argument to the Docker CLI run command. This uses the ${localWorkspaceFolder} variable that is expanded to the containing directory of the local source code:

devcontainer.json:

{
    "name": "Go",
    "dockerFile": "Dockerfile",
    "runArgs": [
        "--env-file", "${localWorkspaceFolder}/.devcontainer/.env"
    ], 

    ...
}
Pero P.
  • 25,813
  • 9
  • 61
  • 85
  • `${localWorkspaceFolder}` is not yet supported when using Clone Repository in Container Volume. – David Dahan Feb 08 '22 at 15:40
  • @DavidD. are you saying this doesn't work with Clone Repository in Container Volume at all or that this technique doesn't work but there is an alternative that does work? – Larry Foulkrod Mar 01 '22 at 17:34
  • @LarryFoulkrod reading [this](https://code.visualstudio.com/docs/remote/devcontainerjson-reference#_variables-in-devcontainerjson) it's written "Not yet supported when using Clone Repository in Container Volume." – David Dahan Mar 01 '22 at 21:22