数据库配置
¥Database configuration
./config/database.js
文件(或 TypeScript 的 ./config/database.ts
文件)用于定义用于存储应用内容的数据库连接。
¥The ./config/database.js
file (or the ./config/database.ts
file for TypeScript) is used to define database connections that will be used to store the application content.
Strapi 应用并不意味着连接到预先存在的数据库、不是由 Strapi 应用创建的数据库,也不是连接到 Strapi v3 数据库。Strapi 团队不会支持此类尝试。尝试连接到不受支持的数据库可能并且很可能会导致数据丢失。
¥Strapi applications are not meant to be connected to a pre-existing database, not created by a Strapi application, nor connected to a Strapi v3 database. The Strapi team will not support such attempts. Attempting to connect to an unsupported database may, and most likely will, result in lost data.
配置结构
¥Configuration structure
/config/database.js|ts
文件接受 2 个主要配置对象:
¥The /config/database.js|ts
file accepts 2 main configuration objects:
-
connection
用于传递给 Knex.js 的数据库配置选项¥
connection
for database configuration options passed to Knex.js -
settings
用于 Strapi 特定的数据库设置¥
settings
for Strapi-specific database settings
connection
配置对象
¥connection
configuration object
范围 | 描述 | 类型 | 默认 |
---|---|---|---|
client | 数据库客户端创建连接。 接受以下值:
| String | * |
connection | 数据库 连接信息 | Knex.Config object<br />Knex.Config Function (experimental) | * |
debug | 显示数据库交换和错误。 | Boolean | false |
useNullAsDefault 可选,仅适用于 SQLite | 使用 NULL 作为默认值 | Boolean | true |
pool 可选 | 数据库池选项 | Object | * |
acquireConnectionTimeout 可选 | 获取连接时 knex 在抛出超时错误之前将等待多长时间(以毫秒为单位) | Integer | 60000 |
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 | 数据库主机名。默认值:localhost 。 | String |
port | 数据库端口 | Integer |
database | 数据库名称。 | String |
user | 用于建立连接的用户名 | String |
password | 用于建立连接的密码 | String |
timezone | 设置当地时间的默认行为。默认值:utc 时区选项 | String |
schema | 设置默认数据库架构。仅用于 Postgres 数据库。 | String |
ssl | 用于 SSL 数据库连接。 使用对象将证书文件作为字符串传递。 | Boolean 或 Object |
根据所使用的数据库客户端,可以设置更多参数(例如,charset
和 collation
代表 mysql)。检查数据库客户端文档以了解哪些参数可用,例如 pg、mysql 和 better-sqlite3 文档。
¥Depending on the database client used, more parameters can be set (e.g., charset
and collation
for mysql). Check the database client documentation to know what parameters are available, for instance the pg, mysql, and better-sqlite3 documentations.
数据库池选项
¥Database pooling options
可以在 ./config/database.js
(或 TypeScript 的 ./config/database.ts
)中找到的 connection.pool
对象用于传递 Tarn.js 数据库池选项并接受以下参数:
¥The connection.pool
object optionally found in ./config/database.js
(or ./config/database.ts
for TypeScript) is used to pass Tarn.js database pooling options and accepts the following parameters:
使用 Docker 时,请将池 min
值更改为 0
,因为 Docker 会终止任何空闲连接,从而无法保留与数据库的任何打开连接(有关更多信息,请参阅 Knex.js 使用的 Tarn.js 池 设置)。
¥When using Docker, change the pool min
value to 0
as Docker will kill any idle connections, making it impossible to keep any open connections to the database (see the Tarn.js pool settings used by Knex.js for more information).
范围 | 描述 | 类型 | 默认 |
---|---|---|---|
min | keepalive 的最小数据库连接数 | Integer | 2 |
max | keepalive 的最大数据库连接数 | Integer | 10 |
acquireTimeoutMillis | 数据库连接尝试超时之前的时间(以毫秒为单位) | Integer | 60000 |
createTimeoutMillis | 创建查询尝试超时之前的时间(以毫秒为单位) | Integer | 30000 |
destroyTimeoutMillis | 销毁查询尝试超时之前的时间(以毫秒为单位) | Integer | 5000 |
idleTimeoutMillis | 空闲数据库连接被销毁之前的时间(以毫秒为单位) | Integer | 30000 |
reapIntervalMillis | 检查要销毁的空闲数据库连接的时间(以毫秒为单位) | Integer | 1000 |
createRetryIntervalMillis | 重试失败的创建操作之前的空闲时间(以毫秒为单位) | Integer | 200 |
afterCreate | 当池获取新连接时执行自定义逻辑的回调函数。 有关详细信息,请参阅 Knex.js 文档 | 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 |
useTypescriptMigrations | 在构建目录而不是 src 目录中查找迁移 | Boolean | false |
使用 useTypescriptMigrations
时,你可以通过在 tsconfig 文件中设置 compilerOptions { allowJs: true }
来继续使用现有的 JavaScript 迁移。
¥When using useTypescriptMigrations
you can continue to use existing JavaScript migrations by setting compilerOptions { allowJs: true }
in your tsconfig file.
配置举例
¥Configuration examples
- PostgreSQL
- MySQL/MariaDB
- SQLite
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
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: {
rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false), // For self-signed certificates
},
},
debug: false,
},
});
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 验证,你将需要使用 ssl:{}
对象和 fs 模块将你的 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(),
},
},
},
});
module.exports = ({ env }) => ({
connection: {
client: 'mysql',
connection: {
host: env('DATABASE_HOST', '127.0.0.1'),
port: env.int('DATABASE_PORT', 3306),
database: env('DATABASE_NAME', 'strapi'),
user: env('DATABASE_USERNAME', 'strapi'),
password: env('DATABASE_PASSWORD', 'strapi'),
ssl: {
rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false), // For self-signed certificates
},
},
debug: false,
},
});
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
connection: {
client: 'sqlite',
connection: {
filename: env('DATABASE_FILENAME', '.tmp/data.db'),
},
useNullAsDefault: true,
debug: false,
},
});
import path from 'path';
export default ({ env }) => ({
connection: {
client: 'sqlite',
connection: {
filename: path.join(
__dirname,
'..',
'..',
env('DATABASE_FILENAME', path.join('.tmp', 'data.db'))
),
},
useNullAsDefault: true,
},
});
数据库中的配置
¥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
(字符串):设置你想要存储数据的环境。默认情况下,它是当前环境(如果你的配置与环境无关,则可以是空字符串)。¥
environment
(string): Sets the environment you want to store the data in. By default it's current environment (can be an empty string if your configuration is environment agnostic). -
type
(字符串):设置你的配置是否适用于api
、plugin
或core
。默认为core
。¥
type
(string): Sets if your configuration is for anapi
,plugin
orcore
. By default it'score
. -
name
(字符串):如果type
是api
或plugin
,则必须设置插件或 api 名称。¥
name
(string): You have to set the plugin or api name iftype
isapi
orplugin
. -
key
(字符串,必需):你要存储的密钥的名称。¥
key
(string, required): The name of the key you want to store.
// 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
(任意,必填):你要存储的值。¥
value
(any, required): The value you want to store.
// 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
文件中包含数据库配置选项。创建新项目时,具有值 mysql
、postgres
或 sqlite
的环境变量 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:
- JavaScript
- TypeScript
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),
},
};
};
import path from 'path';
export default = ({ 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:
- MySQL or MariaDB
- PostgreSQL
- SQLite
# 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
# Database
DATABASE_CLIENT=postgres
DATABASE_HOST=127.0.0.1
DATABASE_PORT=5432
DATABASE_NAME=strapi
DATABASE_USERNAME=strapi
DATABASE_PASSWORD=strapi
DATABASE_SSL=false
# Database
DATABASE_CLIENT=sqlite
DATABASE_FILENAME=.tmp/data.db
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:
-
将你的应用更新到
v4.6.2
或更高版本。参见 upgrades 文档。¥Update your application to
v4.6.2
or a later version. See the upgrades documentation. -
将
./config/database.js
或./config/database.ts
文件的内容替换为前面的 JavaScript 或 TypeScript 代码。¥Replace the contents of your
./config/database.js
or./config/database.ts
file with the preceding JavaScript or TypeScript code. -
将前面代码示例中的环境变量添加到
.env
文件中。¥Add the environment variables from the preceding code example to your
.env
file. -
(可选)添加其他环境变量,例如
DATABASE_URL
和ssl
对象的属性。¥(optional) Add additional environment variables such as
DATABASE_URL
and the properties of thessl
object. -
保存更改并重新启动你的应用。
¥Save the changes and restart your application.
不要覆盖环境变量:HOST
、PORT
、APP_KEYS
、API_TOKEN_SALT
和 ADMIN_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
属性。connectionString
是 connection.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
属性,例如host
和port
,¥overrides the other
connection.connection
properties such ashost
andport
, -
可以通过将该属性设置为空字符串来禁用:
''
。¥can be disabled by setting the property to an empty string:
''
.
按环境管理数据库
¥Database management by environment
Strapi 应用的开发通常包括在本地开发环境中使用本地开发数据库(例如 SQLite
)进行定制。当应用准备好用于另一个环境(例如生产或登台)时,应用将使用不同的数据库实例(通常是 MySQL
、MariaDB
或 PostgreSQL
)进行部署。数据库环境变量允许你切换附加的数据库。切换数据库连接:
¥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:
-
为
MySQL
、MariaDB
和PostgreSQL
设置DATABASE_CLIENT
和DATABASE_URL
的最小值,¥set a minimum of the
DATABASE_CLIENT
andDATABASE_URL
forMySQL
,MariaDB
, andPostgreSQL
, -
或者为
SQLite
设置最小值DATABASE_CLIENT
和DATABASE_FILENAME
。¥or set a minimum of
DATABASE_CLIENT
andDATABASE_FILENAME
forSQLite
.
对于应用的部署版本,数据库环境变量应存储在存储其他密钥的位置。下表给出了数据库环境变量应存储位置的示例:
¥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
- npm
yarn create strapi-app my-project --quickstart
npx create-strapi-app@latest 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
- npm
yarn add better-sqlite3
npm install better-sqlite3
将以下代码添加到你的 /config/database.ts|js
文件:
¥Add the following code to your /config/database.ts|js
file:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
connection: {
client: 'sqlite',
connection: {
filename: path.join(__dirname, '..', env('DATABASE_FILENAME', '.tmp/data.db')),
},
useNullAsDefault: true,
},
});
import path from 'path';
export default ({ 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;