dockerdocker-composedockerfilevscode-devcontainer

Docker Compose set env variable from command


I'm setting up a VSCode dev-container using docker compose. I also have some file myVersion.txt which contains a string. I need this string inside the DockerFile while building the container, but the string has to stay inside myVersion.txt and I'd prefer avoiding copy-pasting it manually into another file like .env or Dockerfile.

Is there a way to achieve this? Something like ENV MY_VERSION=${cat local/file/myVersion.txt}, which obviously does not work

devcontainer.json:

{
  "dockerComposeFile": "./docker-compose.yml",
  "service": "game",
  "workspaceFolder": "/home/node/game",
  "remoteUser": "node",
}

and docker-compose.yml:

version: "3.9"

services:
  game:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ..:/home/node/game
    ports:
      - "3000:3000"

and Dockerfile:

FROM node:20

WORKDIR /

ENV MY_VERSION=???

RUN some_command --argument $MY_VERSION


Solution

  • Not tested, but you could approach it like this:

    Mount the file as volume in your docket-compose.yml:

    volumes:
        - local/file/version.txt:/version.txt
    

    Then in the Dockerfile, you can RUN some-command —version "$(cat /version.txt)"