如何在Rails应用程序中将mysql与docker连接?

sch*_*cho 5 mysql ruby-on-rails docker

我创建了一个使用mysql数据库的Rails应用程序。现在想将它们放入docker容器中。我正在使用docker,docker-machine,docker-compose。

我的docker-compose.yml

db:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD: <%= ENV['MYSQL_ROOT_PASSWORD'] %>
  ports:
    - "3306:3306"

web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - .:/myapp
  ports:
    - "3000:3000"
  links:
    - db
Run Code Online (Sandbox Code Playgroud)

我的config / database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: <%= ENV['MYSQL_ROOT_PASSWORD'] %>
  host: <%= ENV['DB_PORT_3306_TCP_ADDR'] %>
  port: <%= ENV['DB_PORT_3306_TCP_PORT'] %>

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: myapp_production
Run Code Online (Sandbox Code Playgroud)

启动应用程序时

$ docker-compose up
...
sidekiq_1 | Host '172.17.0.5' is not allowed to connect to this MySQL server
...
Run Code Online (Sandbox Code Playgroud)

我的网络环境

$ docker-compose run web env
...
DB_PORT=tcp://172.17.0.3:3306
DB_PORT_3306_TCP=tcp://172.17.0.3:3306
DB_PORT_3306_TCP_ADDR=172.17.0.3
DB_PORT_3306_TCP_PORT=3306
DB_PORT_3306_TCP_PROTO=tcp
WEB_PORT=tcp://172.17.0.6:3000
WEB_PORT_3000_TCP=tcp://172.17.0.6:3000
WEB_PORT_3000_TCP_ADDR=172.17.0.6
WEB_PORT_3000_TCP_PORT=3000
WEB_PORT_3000_TCP_PROTO=tcp
...
Run Code Online (Sandbox Code Playgroud)

我的docker-machine ip

$ docker-machine ip myapp
192.168.99.100
Run Code Online (Sandbox Code Playgroud)

从浏览器访问:http://192.168.99.100:3000,然后看到错误:

Mysql2::Error
Host '172.17.0.6' is not allowed to connect to this MySQL server
Run Code Online (Sandbox Code Playgroud)

172.17.0.3172.17.0.5172.17.0.6,等。为什么他们使用不同的IP?那怎么连接mysql呢?我无法理解hostport写在config/database.yml文件中。

Rod*_*chi 6

就我而言,我在主机中运行Rails,在正式映像docker中运行MySQL。

添加host: 127.0.0.1解决了问题。

config / database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password:
  host: 127.0.0.1
Run Code Online (Sandbox Code Playgroud)


kal*_*elc 5

您必须将容器名称 ( db)添加到主机,例如:

配置/数据库.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: <%= ENV['MYSQL_ROOT_PASSWORD'] %>
  host: db
development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: myapp_production
Run Code Online (Sandbox Code Playgroud)

看看你这个例子:docker-to-rails-with-rbenv


Ste*_*uet 0

IP 由内部 DHCP 服务器分配。这就是为什么他们可以改变......

我建议阅读这篇文章http://blog.carbon Five.com/2015/03/17/docker-rails-docker-compose-together-in-your-development-workflow/,它解释了如何使用主机名配置rails应用程序(而不是 IP)在使用 docker-compose 时正确连接到数据库。