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

Node.js Sequelize连接AWS RDS MySQL与EC2实例及数据库不存在错误解决指南

Fixing "Database Doesn't Exist" Error with Sequelize + AWS RDS MySQL

First, let's tackle the immediate error you're seeing—since you can connect via MySQL Workbench, the database definitely exists, so the issue is almost certainly in how Sequelize is configured. Here's how to debug and fix it:

Step 1: Debug the Root Cause

  • Check Database Name Spelling: In your hardcoded Sequelize setup, you have '*db name*'—make sure this is replaced with the exact name of the database you created in RDS. Even a single typo (like missing underscores or wrong case, though MySQL is usually case-insensitive on most setups) will trigger this error.
  • Verify Configuration Source: If you're using config.json, double-check that the database field under your active environment (development by default) matches the RDS database name. Your code falls back to hardcoded values only if config.use_env_variable isn't set, so ensure you're not pulling from a wrong config entry.
  • Test Network Connectivity from EC2: Even though Workbench works, confirm your EC2 instance can reach the RDS endpoint. SSH into your EC2 and run:
    telnet your-rds-endpoint.us-east-2.rds.amazonaws.com 3306
    
    If this fails, your EC2 security group might not allow outbound traffic to RDS's 3306 port, or the RDS security group isn't whitelisting your EC2's private IP/security group.
  • Fix SSL Dialect Options: Your current ssl:'Amazon RDS' setting is incorrect for Sequelize 6. For AWS RDS, you need to set SSL with a flag to bypass unauthorized certificate checks (since Node.js might not recognize AWS's root CA by default):
    dialectOptions: {
      ssl: {
        rejectUnauthorized: false
      }
    }
    
    A misconfigured SSL setup can sometimes manifest as unexpected connection errors, including "database not found".

Step 2: Correct Sequelize Connection Flow

Here's a clean, secure way to set up the connection (avoid hardcoding sensitive data):

1. Configure config/config.json

Create or update your config file with environment-specific settings (add this to .gitignore to keep secrets safe):

{
  "development": {
    "username": "your-rds-username",
    "password": "your-rds-password",
    "database": "your-rds-db-name",
    "host": "your-rds-endpoint.us-east-2.rds.amazonaws.com",
    "dialect": "mysql",
    "dialectOptions": {
      "ssl": {
        "rejectUnauthorized": false
      }
    },
    "pool": {
      "max": 5,
      "min": 0,
      "acquire": 30000,
      "idle": 10000
    },
    "logging": console.log
  }
}

2. Update Your db/index.js

Use the config file instead of hardcoding values, and add a connection test to catch errors early:

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  // For production, use environment variables (e.g., AWS Secrets Manager)
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  // Use config file values for development
  sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    {
      host: config.host,
      port: config.port || 3306,
      dialect: config.dialect,
      dialectOptions: config.dialectOptions,
      pool: config.pool,
      logging: config.logging,
      language: 'en'
    }
  );
}

// Test the connection immediately
sequelize.authenticate()
  .then(() => console.log('✅ Connected to RDS MySQL successfully!'))
  .catch(err => console.error('❌ Connection failed:', err));

// Load all Sequelize models (if you have them)
fs
  .readdirSync(__dirname)
  .filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

// Set up model associations
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.Sequelize = Sequelize;
db.sequelize = sequelize;

module.exports = db;

3. Final Checks

  • Restart your Node.js app after making changes.
  • Ensure your RDS instance is in the same VPC as your EC2 (or that VPC peering is set up if they're in different VPCs).
  • For production, avoid storing credentials in config.json—use AWS Secrets Manager or environment variables injected into your EC2 instance.

内容的提问来源于stack exchange,提问作者Yasiru Ayeshmantha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:22:28