无法在生产服务器中连接Amazon RDS,但在本地服务器上连接

时间:2018-08-19 07:04:49

标签: python django amazon-web-services amazon-rds

我正在使用Amazon Postgre RDS。当我在本地服务器上连接此RDS时,它工作正常,但是当我将它推到github上并拉到EC2时,出现以下错误:

Traceback (most recent call last):
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run
    self.check_migrations()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 422, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 52, in __init__
    self.build_graph()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 209, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
    if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 254, in cursor
    return self._cursor()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 229, in _cursor
    self.ensure_connection()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
    self.connect()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
    self.connect()
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 189, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/home/ubuntu/myvenv/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not connect to server: Connection timed out
	Is the server running on host "myammaji.cbgocwwown9z.ap-south-1.rds.amazonaws.com" (172.31.0.83) and accepting
	TCP/IP connections on port 5432?

我的settings.py正在关注:

"""
Django settings for backmyitem project.

Generated by 'django-admin startproject' using Django 1.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY'),

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', 'ec2-13-232-57-187.ap-south-1.compute.amazonaws.com']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'feed',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'backmyitem.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'feed.views.notification_context',
            ],

        },
    },

]

WSGI_APPLICATION = 'backmyitem.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': password',
        'HOST': 'myammaji.cbgocwwown9z.ap-south-1.rds.amazonaws.com',
        'PORT': '5432'
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LOGIN_REDIRECT_URL = '/report'

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'saifulcseng@gmail.com'
EMAIL_HOST_PASSWORD = 'N@sara0806196'
EMAIL_USE_TLS = True

STATIC_ROOT = os.path.join(BASE_DIR, "..", "static")
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, "..", "media")
MEDIA_URL = '/media/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

我的数据库,用户名和密码都是正确的,因为我已经在本地服务器上对其进行了测试。

1 个答案:

答案 0 :(得分:1)

假定两个实例都在同一VPC(例如默认VPC)或路由/对等VPC中运行:

确保已创建两个单独的安全组,一个用于EC2实例,一个用于RDS实例。向RDS SG添加入站安全组规则,并允许来自EC2 SG的传入PostgreSQL连接(5432 / tcp)。

如果您通过AWS控制台执行所有操作,所有正确的出站规则将自动应用。

有关RDS网络的更多信息:https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.Scenarios.html#USER_VPC.Scenario1