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

Docker环境变量插值失败求助:无法运行指定Python文件

Docker环境变量插值未生效问题排查与解决

我编写了如下Dockerfile,希望通过环境变量插值指定容器启动时运行的Python文件名:

ARG PYTHON_VERSION=3.7-alpine

# Use the python image as the base image
FROM python:${PYTHON_VERSION}

# set environment to run
ENV ENVIRONMENT={ENVIRONMENT:-"prod"}

# Copy the python files
COPY requirements.txt /app/
COPY prod.py dev.py requirements.txt /app/

# Set the working directory 
WORKDIR /app

# Install the dependencies 
RUN pip install -r requirements.txt

# Set the command to run the python file when the container is started
CMD ["python", "${ENVIRONMENT}.py"]

构建镜像并运行容器时,出现如下错误:

python: can't open file '${ENVIRONMENT}.py': [Errno 2] No such file or directory


问题原因

  1. CMD格式导致变量不解析:Docker的CMD使用JSON数组格式时,会直接将参数原样传递给python命令,不会经过shell的环境变量替换流程,因此${ENVIRONMENT}被当作了文件名的一部分,而非环境变量。
  2. ENV指令语法错误:ENV ENVIRONMENT={ENVIRONMENT:-"prod"}的写法有误,默认值的正确语法应该是${变量名:-默认值},不需要额外嵌套大括号。

解决方法

1. 改用Shell格式的CMD

将JSON格式的CMD改为Shell格式,让Shell负责解析环境变量:

CMD python ${ENVIRONMENT}.py

2. 保持JSON格式,通过Shell执行

如果需要保留JSON数组格式,可以通过调用sh -c来触发Shell解析:

CMD ["sh", "-c", "python ${ENVIRONMENT}.py"]

3. 修正ENV指令的语法

同时把错误的ENV指令修正为:

ENV ENVIRONMENT=${ENVIRONMENT:-prod}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:20:26