我是使用docker的新手,我的问题是使用MySQL和Docker以及环境变量加载Rails 4应用程序。
基本上,我会构建应用程序并运行它。在另一个终端中,我创建mysql数据库和由database.yml使用的用户/密码。这是我运行的步骤:
$ docker-compose build
$ docker-compose up -d
$ docker exec -it poseidon_db_1 bash -l
#root@dockerimg mysql -uroot -proot
mysql> create database poseidon_development;
mysql> CREATE USER 'poseidon_user'@'localhost' IDENTIFIED BY 'poseidon_password';
mysql> CREATE USER 'poseidon_user'@'%' IDENTIFIED BY 'poseidon_password';
mysql> GRANT ALL ON poseidon_development.* TO 'poseidon_user'@'localhost';
mysql> GRANT ALL ON poseidon_development.* TO 'poseidon_user'@'%';
mysql> FLUSH PRIVILEGES;
mysql> exit
#root@dockerimg exit
$ docker-compose run web bundle exec rake db:migrate
database.yml
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: <%= ENV["DATABASE_USERNAME"] %>
password: <%= ENV["DATABASE_PASSWORD"] %>
database: <%= ENV["DATABASE_NAME"] %>
host: db
development:
<<: *default
test:
<<: *default
docker-compose.yml
version: '3.6'
services:
db:
restart: always
image: mysql:5.6.34
ports:
- "3306:3306"
volumes:
- dbdata
env_file:
- .env
dbdata:
image: tianon/true
volumes:
- /var/lib/mysql
web:
build: .
ports:
- '3000:3000'
volumes:
- webdata
links:
- "db"
env_file:
- .env
webdata:
image: tianon/true
volumes:
- ".:/var/www/poseidon"
Dockerfile
FROM ruby:2.3.7
ENV LANG C.UTF-8
RUN apt-get update -qq
RUN apt-get install -y build-essential mysql-client vim
WORKDIR /tmp
ADD Gemfile Gemfile
ADD Gemfile.lock Gemfile.lock
RUN bundle install
ENV APP_ROOT /var/www/poseidon
RUN mkdir -p $APP_ROOT
WORKDIR $APP_ROOT
COPY . $APP_ROOT
RUN chmod a+x .env
EXPOSE 3000
ENTRYPOINT ["bundle", "exec"]
CMD ["rails", "server", "-p", "3000", "-b", "0.0.0.0"]
.env
SECRET_KEY_BASE=xxxxxxxx
RAILS_ENV=development
RAILS_SERVE_STATIC_FILES=true
URL_OPTIONS=domain.com
RECAPTCHA_SECRET_KEY=xxxxxxx
RECAPTCHA_SITE_KEY=xxxxxxx
MAILGUN_API=xxxxxx
MAILGUN_DOMAIN=xxxxxxx
MYSQL_ROOT_PASSWORD=root
DATABASE_USERNAME=poseidon_user
DATABASE_PASSWORD=poseidon_password
DATABASE_NAME=poseidon_development
问题是,当访问http://127.0.0.1
时,我收到Access denied for user '<%= ENV["DATABASE_USERNAME"] %>'@'IP' (using password: YES)
我不知道该怎么办,似乎无法正确加载env var。
任何帮助将不胜感激!
致谢
答案 0 :(得分:0)
我在这个问题上困扰了一两天。在Docker之外一切正常,但由于某种原因,未解析ERB的容器。
这篇文章似乎对您有所帮助:rails database.yml not accepting ERB(我通过Rails not replace ENV's value in database.yml找到了)
我刚刚经历了同样的事情,并且偶然发现了您的帖子。我有 在遵循的教程中,我创建了一个puma.conf文件,该文件 包含以下代码:
ActiveRecord::Base.establish_connection( YAML.load_file( "#{app_dir}/config/database.yml" )[rails_env])
我修改为以下内容,并且一切正常:
require 'erb' ActiveRecord::Base.establish_connection( YAML.load( ERB.new( File.read( "#{app_dir}/config/database.yml" )).result)[rails_env])