Skip to main content

数据库配置

🌐 Database configuration

Page summary:

/config/database 定义了对 SQLite、MySQL 和 PostgreSQL 等支持的数据库的连接、客户端和连接池。

/config/database.js|ts 文件用于定义将用于存储应用内容的数据库连接。

🌐 The /config/database.js|ts file is used to define database connections that will be used to store the application content.

Supported databases

Strapi支持以下数据库:

| 数据库 | 推荐 | 最低 ||------------|-------------|---------|| MySQL | 8.4 | 8.0 || MariaDB | 11.4 | 10.3 || PostgreSQL | 17.0 | 14.0 || SQLite | 3 | 3 |

Strapi 不支持 MongoDB(或任何 NoSQL 数据库),也不支持任何“云原生”数据库(例如 Amazon Aurora、Google Cloud SQL 等)。

🌐 Strapi does not support MongoDB (or any NoSQL databases), nor does it support any "Cloud Native" databases (e.g., Amazon Aurora, Google Cloud SQL, etc.).

Warning

Strapi 应用不适用于连接到预先存在的数据库,即不是由 Strapi 应用创建的数据库,也不适用于连接到 Strapi v3 数据库。Strapi 团队不会支持这种尝试。尝试连接到不受支持的数据库可能,并且很可能会,导致数据丢失。

配置结构

🌐 Configuration structure

/config/database.js|ts 文件接受两个主要的配置对象:

🌐 The /config/database.js|ts file accepts 2 main configuration objects:

connection 配置对象

🌐 connection configuration object

参数描述类型默认
client用于创建连接的数据库客户端。
可接受以下值:
  • sqlite 用于 SQLite 数据库
  • postgres 用于 PostgreSQL 数据库
  • mysql 用于 MySQL 数据库
String-
connection数据库连接信息Object-
debug显示数据库交互和错误。Booleanfalse
useNullAsDefault

可选,仅用于 SQLite
使用 NULL 作为默认值Booleantrue
pool

可选
数据库连接池选项Object-
acquireConnectionTimeout

可选
在获取连接时,knex 在抛出超时错误之前等待的时间(以毫秒为单位)Integer60000
Note

Strapi 仅支持以下客户端值,并且会在将配置传递给 Knex 之前自动将 client 值重写为以下选项:

🌐 Strapi only supports the following client values, and will automatically rewrite the client value to the following options before passing the configuration to Knex: | client 值 | 实际使用的包 ||----------------|-----------------------------------------------------------------|| sqlite | better-sqlite3 || mysql | mysql2 || postgres | pg |

连接参数

🌐 Connection parameters

./config/database.js(对于 TypeScript 为 ./config/database.ts)中找到的 connection.connection 对象用于传递数据库连接信息,并接受以下参数:

🌐 The connection.connection object found in ./config/database.js (or ./config/database.ts for TypeScript) is used to pass database connection information and accepts the following parameters:

参数描述类型
connectionString数据库连接字符串。设置时,会覆盖其他 connection.connection 属性。要禁用请使用空字符串:''
v4.6.2+ 中可用
String
host数据库主机名。默认值:localhostString
port数据库端口Integer
databasefilename数据库名称或文件名。
  • 对于 MySQL 或 PostgreSQL,使用 database 键(配合 hostport 等)。
  • 对于 SQLite,仅提供 `filename`` which points to the database file.
` 字符串
user用于建立连接的用户名String
password用于建立连接的密码String
timezone设置本地时间的默认行为。默认值:utc Timezone optionsString
schema设置默认数据库模式。仅用于 Postgres 数据库。String
ssl用于 SSL 数据库连接。
使用对象将证书文件作为字符串传递。
BooleanObject
Note

根据所使用的数据库客户端,可以设置更多参数(例如,针对 mysqlcharsetcollation)。请查阅数据库客户端文档以了解可用的参数,例如 pgmysqlbetter-sqlite3 文档。

数据库连接池选项

🌐 Database pooling options

./config/database.js(或 TypeScript 的 ./config/database.ts)中可选找到的 connection.pool 对象用于传递 Tarn.js 数据库连接池选项,并接受以下参数:

Caution

在使用 Docker 时,将池 min 的值更改为 0,因为 Docker 会杀死任何空闲连接,使得无法保持与数据库的任何开放连接(有关更多信息,请参见 Knex.js 使用的 Tarn.js pool 设置)。

参数描述类型默认
min要保持的最少数据库连接数Integer2
max数据库保持连接的最大数量Integer10
acquireTimeoutMillis数据库连接尝试超时前的时间(毫秒)Integer60000
createTimeoutMillis创建查询尝试超时前的毫秒数Integer30000
destroyTimeoutMillis在销毁查询尝试超时前的毫秒数Integer5000
idleTimeoutMillis在销毁空闲数据库连接之前的毫秒数Integer30000
reapIntervalMillis检查并销毁空闲数据库连接的时间(毫秒)Integer1000
createRetryIntervalMillis在重试失败的创建操作之前空闲的毫秒数Integer200
afterCreate当连接池获取新连接时执行自定义逻辑的回调函数。

更多信息请参见 Knex.js documentation
Function-

settings 配置对象

🌐 settings configuration object

./config/database.js(或 TypeScript 的 ./config/database.ts)中找到的 settings 对象用于配置 Strapi 特定的数据库设置,并接受以下参数:

🌐 The settings object found in ./config/database.js (or ./config/database.ts for TypeScript) is used to configure Strapi-specific database settings and accepts the following parameters: | 参数 | 描述 | 类型 | 默认值 || --- | --- | --- | --- || forceMigration | 启用或禁用强制数据库迁移。 | Boolean | true || runMigrations | 启用或禁用启动时运行数据库迁移。 | Boolean | true |

配置示例

🌐 Configuration examples

./config/database.js
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
connectionString: env('DATABASE_URL'),
host: env('DATABASE_HOST', '127.0.0.1'),
port: env.int('DATABASE_PORT', 5432),
database: env('DATABASE_NAME', 'strapi'),
user: env('DATABASE_USERNAME', 'strapi'),
password: env('DATABASE_PASSWORD', 'strapi'),
schema: env('DATABASE_SCHEMA', 'public'), // Not required
ssl: env.bool('DATABASE_SSL', false) && {
rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false), // For self-signed certificates
},
},
pool: { min: env.int('DATABASE_POOL_MIN', 2), max: env.int('DATABASE_POOL_MAX', 10) },
debug: false,
},
});
Caution

Strapi 已经注意到有关 服务器 SSL 支持 的问题。为了修复它,你必须将 ssl:{} 对象设置为布尔值以禁用它。具体示例如下:

🌐 Strapi is aware that there is an issue regarding SSL support for the server. In order to fix it, you have to set the ssl:{} object as a boolean in order to disable it. See below for example:

module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
...
ssl: env('DATABASE_SSL', false)
},
},
});

请注意,如果你需要客户端 SSL CA 验证,你将需要使用 fs 模块中的 ssl:{} 对象将你的 CA 证书转换为字符串。你可以参见下面的示例:

🌐 Please note that if you need client side SSL CA verification you will need to use the ssl:{} object with the fs module to convert your CA certificate to a string. You can see an example below:

const fs = require('fs');
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
...
ssl: {
ca: fs.readFileSync(`${__dirname}/path/to/your/ca-certificate.crt`).toString(),
},
},
},
});

数据库中的配置

🌐 Configuration in database

配置文件不适合多服务器环境。在生产中更新配置时,可以使用数据存储来获取和设置设置。

🌐 Configuration files are not multi-server friendly. To update configurations in production you can use a data store to get and set settings.

获取设置

🌐 Get settings

  • environment (字符串):设置你希望存储数据的环境。默认是当前环境(如果你的配置与环境无关,可以为空字符串)。
  • type(字符串):设置你的配置是用于 apiplugin 还是 core。默认是 core
  • name (字符串):如果 typeapiplugin,你必须设置插件或 API 名称。
  • key(字符串,必填):你想要存储的键的名称。
// strapi.store(object).get(object);
// create reusable plugin store variable
const pluginStore = strapi.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'users-permissions',
});
await pluginStore.get({ key: 'grant' });

设置

🌐 Set settings

  • value(任意,必填):你想要存储的值。
// strapi.store(object).set(object);
// create reusable plugin store variable
const pluginStore = strapi.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'users-permissions'
});
await pluginStore.set({
key: 'grant',
value: {
...
}
});

数据库配置中的环境变量

🌐 Environment variables in database configurations

Strapi 版本 v4.6.2 及更高版本在 ./config/database.js./config/database.ts 文件中包含数据库配置选项。当创建新项目时,根据在项目创建过程中选择的数据库,会自动将值为 mysqlpostgressqlite 的环境变量 DATABASE_CLIENT 添加到 .env 文件中。此外,连接到本地开发数据库所需的所有环境变量也会添加到 .env 文件中。以下是生成的配置文件示例:

🌐 Strapi version v4.6.2 and higher includes the database configuration options in the ./config/database.js or ./config/database.ts file. When a new project is created the environment variable DATABASE_CLIENT with the value mysql, postgres, or sqlite is automatically added to the .env file depending on which database you choose during project creation. Additionally, all of the environment variables necessary to connect to your local development database are also added to the .env file. The following is an example of the generated configuration file:

const path = require('path');

module.exports = ({ env }) => {
const client = env('DATABASE_CLIENT', 'sqlite');

const connections = {
mysql: {
connection: {
connectionString: env('DATABASE_URL'),
host: env('DATABASE_HOST', 'localhost'),
port: env.int('DATABASE_PORT', 3306),
database: env('DATABASE_NAME', 'strapi'),
user: env('DATABASE_USERNAME', 'strapi'),
password: env('DATABASE_PASSWORD', 'strapi'),
ssl: env.bool('DATABASE_SSL', false) && {
key: env('DATABASE_SSL_KEY', undefined),
cert: env('DATABASE_SSL_CERT', undefined),
ca: env('DATABASE_SSL_CA', undefined),
capath: env('DATABASE_SSL_CAPATH', undefined),
cipher: env('DATABASE_SSL_CIPHER', undefined),
rejectUnauthorized: env.bool(
'DATABASE_SSL_REJECT_UNAUTHORIZED',
true
),
},
},
pool: { min: env.int('DATABASE_POOL_MIN', 2), max: env.int('DATABASE_POOL_MAX', 10) },
},
postgres: {
connection: {
connectionString: env('DATABASE_URL'),
host: env('DATABASE_HOST', 'localhost'),
port: env.int('DATABASE_PORT', 3306),
database: env('DATABASE_NAME', 'strapi'),
user: env('DATABASE_USERNAME', 'strapi'),
password: env('DATABASE_PASSWORD', 'strapi'),
ssl: env.bool('DATABASE_SSL', false) && {
key: env('DATABASE_SSL_KEY', undefined),
cert: env('DATABASE_SSL_CERT', undefined),
ca: env('DATABASE_SSL_CA', undefined),
capath: env('DATABASE_SSL_CAPATH', undefined),
cipher: env('DATABASE_SSL_CIPHER', undefined),
rejectUnauthorized: env.bool(
'DATABASE_SSL_REJECT_UNAUTHORIZED',
true
),
},
schema: env('DATABASE_SCHEMA', 'public'),
},
pool: { min: env.int('DATABASE_POOL_MIN', 2), max: env.int('DATABASE_POOL_MAX', 10) },
},
sqlite: {
connection: {
filename: path.join(
__dirname,
'..',
env('DATABASE_FILENAME', 'data.db')
),
},
useNullAsDefault: true,
},
};

return {
connection: {
client,
...connections[client],
acquireConnectionTimeout: env.int('DATABASE_CONNECTION_TIMEOUT', 60000),
},
};
};

以下是每个可能数据库对应的 .env 文件数据库相关键的示例:

🌐 The following are examples of the corresponding .env file database-related keys for each of the possible databases:


# Database
DATABASE_CLIENT=mysql
DATABASE_HOST=127.0.0.1
DATABASE_PORT=3306
DATABASE_NAME=strapi
DATABASE_USERNAME=strapi
DATABASE_PASSWORD=strap1
DATABASE_SSL=false

v4.6.2 之前 Strapi 应用的环境变量

🌐 Environment variables for Strapi applications before v4.6.2

如果你使用早于 v4.6.2 的版本启动了你的项目,你可以按照以下程序转换你的 database.js|database.ts 配置文件:

🌐 If you started your project with a version prior to v4.6.2 you can convert your database.js|database.ts configuration file following this procedure:

  1. 将你的应用更新到 v4.6.2 或更高版本。请参阅 升级 文档。
  2. 用上面的 JavaScript 或 TypeScript 代码替换你的 ./config/database.js./config/database.ts 文件的内容。
  3. 将前面代码示例中的环境变量添加到你的 .env 文件中。
  4. (可选)添加额外的环境变量,例如 DATABASE_URL 以及 ssl 对象的属性。
  5. 保存更改并重新启动你的应用。
Caution

不要覆盖环境变量:HOSTPORTAPP_KEYSAPI_TOKEN_SALTADMIN_JWT_SECRET

🌐 Do not overwrite the environment variables: HOST, PORT, APP_KEYS, API_TOKEN_SALT, and ADMIN_JWT_SECRET.

使用 connectionString 的数据库连接

🌐 Database connections using connectionString

许多托管数据库解决方案使用属性 connectionString 将数据库连接到应用。Strapi v4.6.2 及更高版本包括 connectionString 属性。connectionStringconnection.connection 对象中所有数据库属性的串联。connectionString

🌐 Many managed database solutions use the property connectionString to connect a database to an application. Strapi v4.6.2 and later versions include the connectionString property. The connectionString is a concatenation of all the database properties in the connection.connection object. The connectionString:

  • 覆盖其他 connection.connection 属性,例如 hostport
  • 可以通过将属性设置为空字符串来禁用:''

按环境进行数据库管理

🌐 Database management by environment

Strapi 应用的开发通常包括在本地开发环境中使用本地开发数据库(例如 SQLite)进行自定义。当应用准备好部署到其他环境(如生产或预发布环境)时,应用会使用不同的数据库实例部署,通常是 MySQLMariaDBPostgreSQL。数据库环境变量允许你切换所连接的数据库。要切换数据库连接:

🌐 Development of a Strapi application commonly includes customization in the local development environment with a local development database, such as SQLite. When the application is ready for another environment such as production or staging the application is deployed with a different database instance, usually MySQL, MariaDB, or PostgreSQL. Database environment variables allow you to switch the attached database. To switch the database connection:

  • MySQLMariaDBPostgreSQL 设置 DATABASE_CLIENTDATABASE_URL 的最小值,
  • 或者为 SQLite 设置 DATABASE_CLIENTDATABASE_FILENAME 的最小值。

对于已部署的应用版本,数据库环境变量应存储在存储其他密钥信息的地方。下表给出了数据库环境变量应存储的位置示例:

🌐 For deployed versions of your application the database environment variables should be stored wherever your other secrets are stored. The following table gives examples of where the database environment variables should be stored: | 托管选项 | 环境变量存储 ||-------------------------------------------------------|---------------------------------|| 虚拟专用服务器/虚拟机(例如 AWS EC2) | ecosystem.config.js.env || DigitalOcean 应用平台 | Environment Variables 表 || Heroku | Config vars 表 |

数据库安装

🌐 Databases installation

Strapi 让你可以为你的项目选择最合适的数据库。Strapi 支持 PostgreSQL、SQLite 或 MySQL。

🌐 Strapi gives you the option to choose the most appropriate database for your project. Strapi supports PostgreSQL, SQLite, or MySQL.

SQLite

SQLite 是默认的(参见 快速入门指南)且推荐的数据库,用于快速在本地创建应用。

🌐 SQLite is the default (see Quick Start Guide) and recommended database to quickly create an application locally.

在创建应用时安装 SQLite

🌐 Install SQLite during application creation

使用以下命令之一:

🌐 Use one of the following commands:

yarn create strapi-app my-project --quickstart

这将创建一个新项目并在浏览器中启动它。

🌐 This will create a new project and launch it in the browser.

手动安装 SQLite

🌐 Install SQLite manually

在终端中,运行以下命令:

🌐 In a terminal, run the following command:

yarn add better-sqlite3

将以下代码添加到你的 /config/database.ts|js 文件中:

🌐 Add the following code to your /config/database.ts|js file:

./config/database.js
module.exports = ({ env }) => ({
connection: {
client: 'sqlite',
connection: {
filename: path.join(__dirname, '..', env('DATABASE_FILENAME', '.tmp/data.db')),
},
useNullAsDefault: true,
},
});

PostgreSQL

将 Strapi 连接到 PostgreSQL 数据库时,数据库用户需要 SCHEMA 权限。虽然数据库管理员默认具有此权限,但为 Strapi 应用专门创建的新数据库用户将不具备该权限。这会导致在尝试加载管理员控制台时出现 500 错误。

🌐 When connecting Strapi to a PostgreSQL database, the database user requires SCHEMA permissions. While the database admin has this permission by default, a new database user explicitly created for the Strapi application will not. This would result in a 500 error when trying to load the admin console.

要创建具有 SCHEMA 权限的新 PostgreSQL 用户,请使用以下步骤:

🌐 To create a new PostgreSQL user with the SCHEMA permission, use the following steps:

# Create a new database user with a secure password
$ CREATE USER my_strapi_db_user WITH PASSWORD 'password';
# Connect to the database as the PostgreSQL admin
$ \c my_strapi_db_name admin_user
# Grant schema privileges to the user
$ GRANT ALL ON SCHEMA public TO my_strapi_db_user;