imsaiful
imsaiful

Reputation: 1604

Unable to connect Amazon RDS in production server but connect on local server

I am using Amazon Postgre RDS. When I connect this RDS in my local server it is working perfectly fine but when I push it on github and pull on my EC2 then I am getting following error:

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?

My settings.py is following:

"""
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 = '[email protected]'
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"),
]

My DB, username and password all are accurate because I have tested it on the local server.

Upvotes: 1

Views: 1405

Answers (1)

Joe Eig
Joe Eig

Reputation: 353

Assuming both instances are running in the same VPC (like the default VPC) or in routed/peered VPCs:

Make sure you've created two separate security groups, one for the EC2 instance and one for the RDS instance. Add an inbound security group rule to the RDS SG and allow incoming PostgreSQL connections (5432/tcp) originating from the EC2's SG.

If you do everything via the AWS Console, all proper outbound rules will be applied automatically.

More information about RDS networking: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.Scenarios.html#USER_VPC.Scenario1

Upvotes: 1

Related Questions