You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在docker-compose.yml的command字段中使用命令行传入的变量?

Docker Compose 环境变量传递问题

我的配置与操作

docker-compose-test.yml 文件内容

services:
  environment-service:
    image: ubuntu:24.04
    command: "echo 'you should see string as the next string: $DRYRUNG'"

执行的命令

docker-compose --file docker-compose-test.yml run -e DRYRUNG=string environment-service

实际输出

第一次执行(拉取镜像时):

WARNING: The DRYRUNG variable is not set. Defaulting to a blank string.
Pulling environment-service (ubuntu:24.04)...
24.04: Pulling from library/ubuntu
5a7813e071bf: Already exists
Digest: sha256:72297848456d5d37d1262630108ab308d3e9ec7ed1c3286a32fe09856619a782
Status: Downloaded newer image for ubuntu:24.04
Creating mbonnet_environment-service_run ... done
you should see string as the next string:

第二次执行(镜像已存在):

WARNING: The DRYRUNG variable is not set. Defaulting to a blank string.
Creating mbonnet_environment-service_run ... done
you should see string as the next string:

预期输出

Creating mbonnet_environment-service_run ... done
you should see string as the next string: string

系统信息

$ docker-compose --version
docker-compose version 1.29.2, build unknown
$ docker -v
Docker version 28.0.0, build f9ced58
$ lsb_release -a 
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 24.04.2 LTS
Release:        24.04
Codename:       noble

需求说明

不想在当前Shell中设置全局环境变量,也不想通过.env文件配置,希望直接通过docker-compose命令行传入任意值,实际用途是在容器内作为命令行工具的参数。


解决方法

问题出在command的引号使用:原配置中用双引号包裹命令,本地Shell会先解析$DRYRUNG变量(此时本地未设置该变量,所以被替换为空),再把空值传到容器里。要让变量在容器内被解析,有两种修改方式:

方式1:将命令的双引号改为单引号

修改docker-compose-test.yml:

services:
  environment-service:
    image: ubuntu:24.04
    command: 'echo "you should see string as the next string: $DRYRUNG"'

单引号会阻止本地Shell解析变量,变量会原封不动传到容器,由容器内的Shell解析。

方式2:使用数组形式定义命令

用数组形式避免Shell解析,直接指定执行的命令和参数:

services:
  environment-service:
    image: ubuntu:24.04
    command: ["sh", "-c", "echo 'you should see string as the next string: $DRYRUNG'"]

这种方式下,sh -c会在容器内启动Shell并执行后续命令,此时容器内已通过-e设置了DRYRUNG变量,就能正确输出预期内容。

内容的提问来源于stack exchange,提问作者Michael Bonnet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:43:24