温馨提示×

centos nodejs如何连数据库

小樊
41
2026-10-08 18:14:50
栏目: 编程语言

在 CentOS 上使用 Node.js 连接数据库,通常取决于你用的是哪种数据库(MySQL / PostgreSQL / MongoDB 等)。下面我以 最常见的几种 为例,给你完整说明。


一、准备工作(CentOS)

1. 安装 Node.js

# 使用 NodeSource(推荐)
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs

# 验证
node -v
npm -v

2. 初始化项目

mkdir node-db-demo
cd node-db-demo
npm init -y

二、连接 MySQL(最常见)

1. 安装 MySQL 驱动

npm install mysql2

2. 示例代码(mysql2)

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'your_password',
  database: 'test_db'
});

connection.connect(err => {
  if (err) {
    console.error('连接失败:', err);
    return;
  }
  console.log('MySQL 连接成功');
});

connection.query('SELECT 1 + 1 AS result', (err, results) => {
  if (err) throw err;
  console.log(results);
});

connection.end();

✅ CentOS 注意

  • 确保 MySQL 已启动:
systemctl start mysqld
systemctl enable mysqld
  • 防火墙放行(远程连接时):
firewall-cmd --add-port=3306/tcp --permanent
firewall-cmd --reload

三、连接 PostgreSQL

1. 安装依赖

npm install pg

2. 示例代码

const { Client } = require('pg');

const client = new Client({
  host: 'localhost',
  user: 'postgres',
  password: 'your_password',
  database: 'test_db',
  port: 5432
});

client.connect()
  .then(() => console.log('PostgreSQL 连接成功'))
  .catch(err => console.error(err));

client.query('SELECT NOW()', (err, res) => {
  if (err) throw err;
  console.log(res.rows);
  client.end();
});

四、连接 MongoDB

1. 安装依赖

npm install mongodb

2. 示例代码

const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    console.log('MongoDB 连接成功');
    const db = client.db('test_db');
    const col = db.collection('users');
    const data = await col.find({}).toArray();
    console.log(data);
  } finally {
    await client.close();
  }
}

run();

五、常见问题(CentOS 特有)

1. 连接被拒绝

  • 数据库没启动
  • 绑定地址错误(MySQL 的 bind-address)
  • 防火墙未放行端口

2. 远程连接失败

修改数据库配置:

# MySQL
bind-address = 0.0.0.0

3. SELinux 阻止

setsebool -P httpd_can_network_connect_db 1

六、推荐做法(生产环境)

  • 使用 连接池
  • 密码放环境变量(.env + dotenv)
  • 使用 ORM(如 Sequelize / Prisma / TypeORM)

如果你告诉我:

  • ✅ 用的 哪种数据库
  • ✅ CentOS 版本(7 / 8 / Stream)
  • ✅ 本地还是远程连接

我可以直接给你 可运行的完整示例。

0 踩