How to connect mysql to connecting rails to docker?

I created a rails application using mysql database. Now I want to put them in a docker container. I am using docker, docker-machine, docker-compose.

My 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

My 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

When downloading the application

$ docker-compose up
...
sidekiq_1 | Host '172.17.0.5' is not allowed to connect to this MySQL server
...

My website

$ 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
...

My ip docker

$ docker-machine ip myapp
192.168.99.100

Access from the browser: http://192.168.99.100:3000and then I saw an error:

Mysql2::Error
Host '172.17.0.6' is not allowed to connect to this MySQL server

172.17.0.3, 172.17.0.5, 172.17.0.6Etc. Why do they use different ips? Then how to connect mysql? I can not understand hostand portrecorded in the file config/database.yml.

+4
source share
3 answers

In my case, I run Rails on the host, and MySQL in docker is the official image.

host: 127.0.0.1 .

/database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password:
  host: 127.0.0.1
+2

(db) , :

/database.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

: docker-to-rails-with-rbenv

+1

IP addresses are assigned by the internal DHCP server. That's why they can change ...

I would recommend reading this post http://blog.carbonfive.com/2015/03/17/docker-rails-docker-compose-together-in-your-development-workflow/ , which explains how to configure the rails application with using the host name (not IP addresses) to properly connect to the database when using docker layout.

0
source

Source: https://habr.com/ru/post/1615154/


All Articles