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

如何通过Windows批处理向Docker Compose传递参数?参数为空求助

问题描述

我希望通过Windows批处理文件构建Docker Compose环境,将用户名、密码参数传递给Grafana的环境变量,但运行脚本后参数未生效,变量为空。

我的批处理脚本

@echo off
set arg1=%1
set arg2=%2

IF "%arg1%" == "" GOTO wrongPara
IF "%arg2%" == "" GOTO wrongPara
set ADMIN_USER="%arg1%"
set ADMIN_PASSWORD="%arg2%"
docker-compose build --no-cache
docker-compose up --build --force-recreate
GOTO end

:wrongPara
echo All Parameters are needed. $1 = Username, $2 = Password

:end
echo Finished

Docker Compose配置

grafana:
    image: grafana/grafana
    hostname: grafana
    container_name: grafana
    ports:
      - "3000:3000"
    links:
      - prometheus
    depends_on:
      - prometheus
    restart: always
    environment:
      - GF_SECURITY_ADMIN_USER=${ADMIN_USER}
      - GF_SECURITY_ADMIN_PASSWORD=${ADMIN_PASSWORD}

运行命令:

install.bat admin password

期望设置Grafana用户为"admin"、密码为"password",但两者均为空,请问问题出在哪里?


问题原因与解决方案

问题出在两个核心点:

  1. 批处理变量设置冗余引号
    你在定义ADMIN_USER和ADMIN_PASSWORD时,给变量值套了双引号,导致实际传递的是带引号的字符串(如"admin")。Grafana会将引号识别为用户名/密码的一部分,而Docker Compose解析时可能出现异常,最终导致变量为空。

修改批处理的变量设置行,去掉多余引号:

set ADMIN_USER=%arg1%
set ADMIN_PASSWORD=%arg2%
  1. Windows批处理环境变量无法直接被Docker Compose读取
    Docker Compose在Windows环境下,默认不会自动加载批处理脚本内临时设置的环境变量。推荐两种可靠的解决方式:

方案一:使用.env文件(推荐)

在批处理中临时生成.env文件,让Docker Compose自动加载变量:

@echo off
set arg1=%1
set arg2=%2

IF "%arg1%" == "" GOTO wrongPara
IF "%arg2%" == "" GOTO wrongPara
echo ADMIN_USER=%arg1% > .env
echo ADMIN_PASSWORD=%arg2% >> .env
docker-compose build --no-cache
docker-compose up --build --force-recreate
REM 可选:运行完成后删除.env文件
REM del .env
GOTO end

:wrongPara
echo All Parameters are needed. $1 = Username, $2 = Password

:end
echo Finished

方案二:直接在命令行传递环境变量

修改批处理中的docker-compose调用,直接将变量传递给容器:

@echo off
set arg1=%1
set arg2=%2

IF "%arg1%" == "" GOTO wrongPara
IF "%arg2%" == "" GOTO wrongPara
docker-compose build --no-cache
docker-compose -e GF_SECURITY_ADMIN_USER=%arg1% -e GF_SECURITY_ADMIN_PASSWORD=%arg2% up --build --force-recreate
GOTO end

:wrongPara
echo All Parameters are needed. $1 = Username, $2 = Password

:end
echo Finished

验证修改

修改后重新运行脚本,进入Grafana容器查看环境变量确认设置:

docker exec grafana env | grep GF_SECURITY

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:50:50