How can I use an env file to pass environment variables into a standalone vscode remote container?

Viewed 7609

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?

1 Answers

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"
    ], 

    ...
}
Related