You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django连接AWS RDS失败:连接超时问题排查与解决

Django连接AWS RDS PostgreSQL超时问题

问题描述

跟随Django教程学习时,无法连接AWS RDS PostgreSQL数据库,settings.py中的数据库配置如下:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'masteruser',
        'PASSWORD': 'passKode',
        'HOST': 'w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com',
        'PORT': '5432'
    }
}

执行命令python manage.py migrate时触发OperationalError连接超时,报错详情如下:

Performing system checks...

System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection
    self.connect()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 269, in get_new_connection
    connection = self.Database.connect(**conn_params)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com" (172.31.11.179), port 5432 failed: Connection timed out
        Is the server running on that host and accepting TCP/IP connections?


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.10/threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 136, in inner_run
    self.check_migrations()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/core/management/base.py", line 574, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__
    self.build_graph()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations
    if self.has_table():
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table
    with self.connection.cursor() as cursor:
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 330, in cursor
    return self._cursor()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 306, in _cursor
    self.ensure_connection()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 288, in ensure_connection
    with self.wrap_database_errors:
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection
    self.connect()
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 269, in get_new_connection
    connection = self.Database.connect(**conn_params)
  File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: connection to server at "w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com" (172.31.11.179), port 5432 failed: Connection timed out
        Is the server running on that host and accepting TCP/IP connections?

使用环境:Python 3.10、Ubuntu 22.04。

错误解析

这个错误说明Django程序无法在指定时间内和AWS RDS PostgreSQL实例建立网络连接,核心原因是网络层面的连通性受阻——不是账号密码或配置参数错误(如果是后者会报身份验证失败,而非超时)。

解决方案

1. 检查AWS RDS安全组配置

AWS RDS的安全组默认拒绝所有外部访问,必须手动允许你的本地IP访问5432端口:

  • 登录AWS控制台,进入RDS服务找到目标实例
  • 点击“连接与安全性”标签,查看关联的安全组
  • 进入安全组的入站规则配置,添加一条规则:
    • 类型:PostgreSQL(端口5432)
    • 来源:选择“我的IP”,或手动输入本地公网IP(Ubuntu终端执行curl ifconfig.me可获取)
    • 保存规则

2. 验证本地到RDS的网络连通性

在Ubuntu终端执行以下命令测试端口是否可达:

# 使用telnet测试
telnet w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com 5432
# 或使用nc命令
nc -zv w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com 5432

如果返回“连接超时”,说明网络通路有问题,回到安全组或本地防火墙排查;如果返回“Connected”,则网络没问题,继续排查其他项。

3. 检查本地Ubuntu防火墙设置

Ubuntu默认启用ufw防火墙,可能会阻止出站的5432端口请求:

  • 临时关闭防火墙测试:sudo ufw disable,然后重新执行python manage.py migrate
  • 如果关闭后可以连接,添加允许出站到5432端口的规则:
    sudo ufw allow out to any port 5432
    sudo ufw enable
    

4. 确认RDS实例状态和端点信息

  • 检查RDS实例状态是否为“可用”(创建中或维护中会无法连接)
  • 确认settings.py中的HOST地址和RDS实例的“端点”完全一致,不要有拼写错误或多余后缀
  • 确认RDS实例的数据库引擎是PostgreSQL,端口确实是5432(修改过默认端口需同步更新配置)

5. 排查VPC配置(RDS在私有子网时)

如果RDS部署在VPC私有子网,本地机器无法直接访问,可选择以下方案:

  • 将RDS实例移到公有子网
  • 配置VPC NAT网关和路由表,让私有子网的RDS可被外部访问
  • 使用AWS VPN、Direct Connect或SSH端口转发的方式连接到私有子网内的RDS

内容的提问来源于stack exchange,提问作者MN.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 14:54:55