Docker Compose强制变量替换报错:无效插值格式问题排查
${VAR?err} in Docker Compose Environment Variables I’ve run into exactly this issue before! The ${VAR?err} and ${VAR:?err} variable validation syntax is indeed supported in Docker Compose, but there’s a critical gotcha here: you need to wrap the entire environment variable value in quotes when using this syntax in a single-line environment entry. Without quotes, Compose misinterprets the ? and the error message as part of an invalid interpolation pattern.
Fix for Your Minimal Reproducible Example
Update your docker-compose.yml to wrap the environment value in double quotes:
version: "3.4" services: hello: image: hello-world environment: - "TEST=${TEST?err}"
Now when you run docker-compose up without setting the TEST variable, you’ll get the expected error: TEST: err instead of the interpolation format error.
Fix for Your Original JAVA_OPTS Configuration
Apply the same quoting fix to your longer JAVA_OPTS line:
environment: - >- "JAVA_OPTS= -DMYSQL_USER=${MYSQL_USER:?MYSQL_USER_NOT_SET} -DMYSQL_PASSWORD=${MYSQL_PASSWORD:?MYSQL_PASSWORD_NOT_SET} -DMYSQL_URL=db:3306/${MYSQL_DATABASE:?MYSQL_DATABASE_NOT_SET}"
Why This Works
Without quotes, Docker Compose tries to parse the entire ${TEST?err} string as an interpolation expression. It recognizes ${VAR} but doesn’t expect the ?err suffix as part of its interpolation grammar, hence the "invalid interpolation format" error. Wrapping the value in quotes tells Compose to treat the entire string as a single value, allowing the variable validation syntax to be processed correctly.
内容的提问来源于stack exchange,提问作者Redline

