【Python】EC2にubuntuでDjangoとRDS(mysql)を接続する方法

こんにちは、nishi_talk(@nishi_talk)です。
Djangoを使うためにEC2にubuntuの環境を構築。RDSで作ったmysqlと連携したかったのですが、設定でちょっとハマってしまったので、今回は備忘録として対処法をご紹介します。




前提条件

以下はインストール・設定済みの状態です。

EC2内環境

ubuntu
python 3.6.4
Django 2.1.4

RDS環境

MySQL エンジンバージョン 5.6.41

RDS環境の設定方法

RDS環境の設定方法はこちらの記事に丁寧に書かれているので、参照しながら設定。

Django、Amazon RDS(MariaDB)に接続する



Djangoとデータベースの接続

setting.py内にDjangoとMariaDBを繋ぐ設定。
各々の環境に合わせて設定してください。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydjango',
        'USER': 'マスターユーザー',
        'PASSWORD': 'マスターユーザーパスワード',
        'HOST': '詳細で確認したエンドポイント',
        'PORT': '3306',
    }
}

migareteしたときにログにエラーが表示。

$ python manage.py migrate

Traceback (most recent call last):
  File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
    self.connect()
  File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection
    return Database.connect(**conn_params)
  File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/site-packages/MySQLdb/__init__.py", line 85, in Connect
    return Connection(*args, **kwargs)
  File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/site-packages/MySQLdb/connections.py", line 208, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2006, "Can't connect to MySQL server on 'xxxxxxxxxxxxxxxxxxxxx' (110)")
・
・
・
django.db.utils.OperationalError: (2006, "Can't connect to MySQL server on 'xxxxxxxxxxxxxxxxxxxxx' (110)")

対処した方法

エラーのログを見ると、どうやらサーバーに接続できてないみたい。

ってことで、まずはEC2からRDSで作成したインスタンスに接続できるか確認。
EC2にsshで接続して、mysqlに接続できるか確認。

$ mysql -h エンドポイント -P 3306 -u root -p

接続が成功の場合はこんな感じの表示になります。

Enter password: ←ここに設定したパスワードを入力
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 5.6.41 Source distribution

Copyright (c) 2000, 2018, 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>



mysqlのコマンドを使えるようにする

私が接続できなかった時は、mysqlのコマンドが使えなかったので、mysql-clientをインストールすると接続できました。

$ sudo apt-get install mysql-client

AWSのセキュリティーグループの設定

それでも接続できない場合、AWSのセキュリティーグループの設定を確認。

EC2からRDS(MySQL)に接続できない。セキュリティグループの設定について・・・

mysqlコマンドで接続ができたら、djangoを使って接続できるか確認します。

$ python manage.py migrate
ubuntu@ip-172-31-44-21:~/Instagram_Report/instagram_report_site/instagram_report_site$ python3 /home/ubuntu/Instagram_Report/instagram_report_site/manage.py migrate
System check identified some issues:
・
・
・

Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

今度は無事に接続できました。