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

Docker中/run/secrets目录文件遍历失败的排查与解决

Docker容器脚本遍历目录文件变量为空问题解决

问题现象

基于Alpine镜像(Docker 26.1.3、Docker Compose v2.27.0环境),用户在容器ENTRYPOINT调用的脚本中尝试遍历/run/secrets/users目录下的文件,脚本内容如下:

#!/bin/sh
…
cd /run/secrets/users
ls -l # 输出显示目录下存在file1、file2等文件

for username in *; do
      echo "username is «$username»" # 此处$username为空
done

执行后ls -l能正常显示目录下的文件,但for循环中的$username始终为空,无法获取到文件名。

问题原因

问题出在Docker构建阶段:脚本通过heredoc方式写入时,未转义的$username被Docker构建过程提前展开,而此时该变量并未定义,最终导致脚本中的$username被替换为空字符串。

解决方法

有两种可行的解决方式:

  • 方式一:转义变量
    将脚本中的$username改为$$username,避免构建时被提前展开:
    #!/bin/sh
    …
    cd /run/secrets/users
    ls -l
    
    for username in *; do
          echo "username is «$$username»"
    done
    
  • 方式二:使用单引号包裹heredoc分界符
    在COPY指令的heredoc中,用单引号包裹分界符(如START),这样Docker构建时不会解析heredoc内的变量:
    COPY --chmod=+x <<-'START' /bin/start.sh
    …
    cd /run/secrets/users
    ls -l
    
    for username in *; do
          echo "username is «$username»" # "$username" 可正常工作
    done
    …
    START
    
    注意:分界符START必须用单引号包裹,且分界符前后不能有多余空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:27:06