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

执行docker run命令报错'$'不是有效端口号问题求助

问题原因

报错Error: '$' is not a valid port number的核心原因是**$PORT变量没有被Shell解析,gunicorn直接拿到了字面量的$PORT作为端口参数**,触发格式校验错误。通常有两种常见诱因:

  • 你修改Dockerfile.prod后,没有重新构建镜像并推送到Heroku容器注册表,运行的仍是旧版本镜像:旧镜像的CMD大概率使用了不支持变量解析的exec格式(即带方括号的写法,Docker的exec格式CMD不会主动调用Shell解析环境变量)
  • 构建镜像时未指定使用Dockerfile.prod,实际用了其他配置错误的Dockerfile构建镜像

解决步骤

  1. 首先修改CMD写法,强制调用Shell解析变量,避免格式兼容问题,将你Dockerfile中的CMD替换为以下内容:
CMD ["sh", "-c", "gunicorn drf_project.wsgi:application --bind 0.0.0.0:$PORT"]
  1. 显式指定使用Dockerfile.prod重新构建镜像:
docker build -f Dockerfile.prod -t registry.heroku.com/lit-sierra-68791/web:latest .
  1. 将新构建的镜像推送到Heroku容器注册表:
docker push registry.heroku.com/lit-sierra-68791/web:latest
  1. 重新执行你的run命令即可正常运行。

可选验证步骤

你可以先在本地测试构建后的镜像是否正常,避免推送后仍有问题:

# 本地运行刚构建的镜像测试
docker run --name django-tdd-test -e "PORT=8765" -p 8008:8765 registry.heroku.com/lit-sierra-68791/web:latest

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:15:03