railsからmysqlにアクセスできない
解決
/sbin/ip route|awk '/default/ { print $3 }'
を実行し、取得したIPを database.ymlの host
に記載する。
$ docker-compose exec [container name of rails] sh
# /sbin/ip route|awk '/default/ { print $3 }'
192.168.112.1
How to get the IP address of the docker host from inside a docker container - Stack Overflow
事象
rails test
を実行しようとすると、(別コンテナの)mysqlに接続できないエラーが発生する。
/usr/local/bundle/gems/mysql2-0.4.10/lib/mysql2/client.rb:89:in `connect': Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory") (Mysql2::Error)
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: root
password: pass
host: <%= ENV['DOCKER_HOST'].to_s[/\d+\.\d+\.\d+\.\d+/] || "localhost" %>
# test ---------------------
test_default: &test_default
<<: *default
database: test
test_read:
<<: *test_default
test_write: &test_write
<<: *test_default
test:
<<: *test_write
調査
docker containerからリモートのMySQL dbに接続します - コードログ にリモートのMySQLに接続する方法が記載されている。
ローカルに接続するつもりで検証していたが、結果、別コンテナのmysqlに接続できた(???)
tips
Railsでデータベースの内容を確認する方法 - Qiita
rails dbconsole
のコマンドで、rails経由でDB各種のクライアントを使用できる
# RAILS_ENV=test rails dbconsole
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 16
Server version: x.x.x-log MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [door_test]>