I'm working on a Node.js project (a Discord bot), and I want the version from package.json to be automatically inserted into docker-compose.yml as a Docker image tag.
Something like this:
services:
bot-dev:
image: "bot-dev:%npm_package_version%"
command: npm run dev
This means that when the version in package.json changes (for example, after an npm version patch), Docker Compose automatically inserts the new value, without having to manually generate the .env file.
Currently, I use workarounds, such as docker compose --env-file .env.version up. bot-dev, but I'm wondering if there's a simple or built-in way, for example, supporting something like %npm_package_version% or ${npm_package_version} directly in docker-compose.yml?
The goal is to implement version autocompletion without hacks or external scripts, so that Compose can use package.json as the source of truth.
Is there a way to do this natively in Docker Compose,
or do I still need to generate .env/CLI variables before running?
I tried substituting the version from package.json directly into docker-compose.yml:
image: "bot-dev:%npm_package_version%"
I expected Docker Compose to automatically take the value from package.json.version (similar to how npm scripts see %npm_package_version%).
However, Compose doesn't insert this variable because it doesn't know about package.json.
I tried the following options:
manually passing the VERSION via PowerShell:
$env:VERSION=(node -p "require('./package.json').version") docker compose upgenerate
.envfile before running:echo VERSION=$(node -p "require('./package.json').version") > .env docker compose up
But it was throwing an error because of the VERSION and the filename, directory name, or volume label syntax is incorrect.
.scriptsentry containingdocker compose ..., so that those env vars are automatically set?docker compose -f docker-compose.yml up? Then Compose will be able to see the value in package?npm runadds those vars to the current env, you can preview this withnpm run env. So if your script is run via npm,$npm_package_versionwill be set.npm runso that variables like$npm_package_versionwould automatically be captured. I thought Docker Compose was somehow pulling the version frompackage.jsonon its own, and I spent two days agonizing over it until I realized the solution was literally in one line. 🙂 Thanks again for the direction! 🙌