首页 > 解决方案 > 如何将 heroku config vars 传递给 docker build?

问题描述

我正在尝试使用heroku.yml. 这是我的yml设置

setup:
  addons:
    - plan: cleardb-mysql
      as: DATABASE
build:
  docker:
    web: Dockerfile
  config:
    RAILS_ENV: development
    DATABASE_URL: mysql2://abcdef:1234567@somewhere-someplace-123.cleardb.net/heroku_abcdefg123456
run:
  web: bin/rails server -p $PORT -b 0.0.0.0

我使用 MySQL 作为数据库。Dockerfile这是 Heroku 用来构建图像的我的。

FROM ruby:2.6.5-alpine

ARG DATABASE_URL
ARG RAILS_ENV
# Adding the required dependencies
# Installing Required Gems
# Other Configs...
# Copying Gem Files
COPY Gemfile Gemfile.lock ./
# Installing Gems
RUN bundle install --jobs=4 --retry=9
# Copying package and package.lock
COPY package.json yarn.lock ./
# Installing node_modules
RUN yarn
# Copy everything to the from current dir to container_root
COPY . ./
#Compiling assets
RUN bundle exec rake assets:precompile # this precompilation step need DATABASE_URL
CMD ["rails", "server", "-b", "0.0.0.0"]

这按预期工作,但问题是我必须在heroku.yml文件中传递数据库字符串。有没有办法可以引用 Heroku 中声明的配置变量?

我试过了,但它不起作用,因为文档还说在 Heroku 中声明的 config-vars 在构建时不可用。

setup:
  addons:
    - plan: cleardb-mysql
      as: DATABASE
build:
  docker:
    web: Dockerfile
  config:
    RAILS_ENV: $RAILS_ENV
    DATABASE_URL: $DATABASE_URL
run:
  web: bin/rails server -p $PORT -b 0.0.0.0

这个问题可能的解决方法是什么?

标签: dockerherokuruby-on-rails-5

解决方案


在不使用 heroku.yml 的情况下,一种可能的解决方案是在 Dockerfile 中包含 env 变量。
Java 代码示例:

CMD java -Dserver.port=$PORT -DmongoDbUrl=$MONGODB_SRV  $JAVA_OPTS -jar /software/myjar.jar

您需要在本地构建映像,将其推送并发布到 Heroku Registry:当它运行时,会注入 Config Vars(即 MONGODB_SRV)


推荐阅读