docker上のrailsアプリケーションからローカル上のmysqlに接続できない問題
環境
問題
すでにrailsはdockerで起動済み
railsアプリケーションにアクセスしようとするとdbの接続エラーが出てくる
$ curl 0.0.0.0:3000/index Puma caught this error: Can't connect to MySQL server on 'xx.xx.xx.xx' (110 "Connection timed out") (Mysql2::Error::ConnectionError)
mysqlコマンドで外部からアクセスできるか確認
# mysql -h xx.xx.xx.xx -uroot -p Enter password: ERROR 2003 (HY000): Can't connect to MySQL server on 'xx.xx.xx.xx' (110)
できないぽ
解決策
全てを受け入れるようにしてみる(セキュリティ的にやばい)
参照:MySQLをiptablesで安全に外部公開する設定 | システムガーディアン株式会社
1. bind-addressで許可する
$ vim /etc/my.cnf bind-address = 0.0.0.0 # bind-address = 127.0.0.1 //コメントアウトしておく # bind-address = 10.x.x.xxx // 停止 sudo mysqladmin -uroot -p shutdown // 起動 sudo mysqld_safe &
確認
# mysql -h xx.xx.xx.xx -uroot -p Enter password: ERROR 2003 (HY000): Can't connect to MySQL server on 'xx.xx.xx.xx' (110)
できないぽ
んんー?
2. 初心にもどりAWSのセキュリティグループ
空いているポートを確認
$ nmap xx.xx.xx.xx Starting Nmap 6.40 ( http://nmap.org ) at 2019-07-10 11:16 JST Nmap scan report for mail.xxx.jp (xx.xx.xx.xx) Host is up (0.00050s latency). Not shown: 996 filtered ports PORT STATE SERVICE 22/tcp open ssh 80/tcp closed http 443/tcp open https 8002/tcp closed teradataordbms Nmap done: 1 IP address (1 host up) scanned in 4.46 seconds
お?3306が空いてないぞ
AWSのセキュリティグループで3006を全てに解放(セキュリティやば過ぎ)
$ nmap xx.xx.xx.xx Starting Nmap 6.40 ( http://nmap.org ) at 2019-07-10 11:16 JST Nmap scan report for mail.xxx.jp (xx.xx.xx.xx) Host is up (0.00050s latency). Not shown: 996 filtered ports PORT STATE SERVICE 22/tcp open ssh 80/tcp closed http 443/tcp open https 3306/tcp open mysql 8002/tcp closed teradataordbms Nmap done: 1 IP address (1 host up) scanned in 4.46 seconds
確認
# mysql -h xx.xx.xx.xx -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 7 Server version: 5.5.56-MariaDB MariaDB Server Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>
とりあえずいけたから、次はセキュリティ面を解決してかないと。