Configuring environment variables prior to creation of dev container

Viewed 824

I am trying to integrate the Remote - Containers with my docker-compose.yaml.

However, my compose file is making use of the variable substitution feature.

services:
    command: yarn server
    environment:
        MONGO_URI: mongodb://database:27017/todo
    ports:
        - ${SERVER_PORT}:3000
        - ${SERVER_DEBUG_PORT}:9320

Typically I set these variables from a Makefile that wraps the docker-compose commands I run to start my development environment.

How can I set these environment variables before the extension creates the Dev Container via docker-compose?

I've attempted to use the initializeCommand in the following ways.

devcontainer.json

"initializeCommand": ". ./env.sh"
"initializeCommand": "source env.sh"

I also attempted to use remoteEnv in the devcontainer.json.

I also attempted to set settings.terminal.integrated.env.linux.

1 Answers

It doesn't seem possible to pass env created in the initializeCommand as env variable to the docker build command. My solution is to create an env file in the initializeCommand and pass it with the build context.

Here is the .devcontainer/devcontainer.json

{
  "build": {
    "dockerfile": "Dockerfile",
    "args": {
      "USERNAME": "${localEnv:USER}"
    }
  },
  "initializeCommand": "echo -e \"USERNAME=$USER\nUSER_UID=$(id -u $USER)\nGROUPNAME=$(id -gn $USER)\nGROUP_GID=$(id -g $USER)\" > .devcontainer/.env"
}

And in the Dockerfile

FROM xxx

ARG USERNAME=user
USER root

# Copy the .env file to the container
COPY .env /tmp/.env
# Source to use it
RUN source /tmp/.env && rm /tmp/.env && \
    if getent passwd $USERNAME; then userdel -f $USERNAME; fi && \
    if getent group $GROUPNAME; then groupdel $GROUPNAME; fi && \
    groupadd --gid $GROUP_GID $GROUPNAME && \
    useradd --uid $USER_UID --gid $GROUP_GID -m $USERNAME && \
    echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \
    chmod 0440 /etc/sudoers.d/$USERNAME && \
    chown $(eval echo ~$USERNAME) && \
    chmod 755 $(eval echo ~$USERNAME)

USER $USERNAME
Related