如何在 Docker 中使用 Prisma
本指南指导你在 Docker 环境中设置 Prisma ORM 应用。你将学习如何配置 Node.js 项目、集成 Prisma 进行数据库管理,以及如何使用 Docker Compose 编排应用。最终,你将拥有一个在 Docker 容器中运行的功能齐全的 Prisma 应用。
¥This guide walks you through setting up a Prisma ORM application within a Docker environment. You'll learn how to configure a Node.js project, integrate Prisma for database management, and orchestrate the application using Docker Compose. By the end, you'll have a fully functional Prisma application running in a Docker container.
先决条件
¥Prerequisites
-
¥Docker and Docker Compose installed
-
Node.js 版本:一个 兼容的 Node.js 版本,Prisma 6 需要。
¥Node.js version: A compatible Node.js version, required for Prisma 6.
开始之前,请确保本地没有运行 PostgreSQL 服务,并且以下端口可用以避免冲突:5432
(PostgreSQL)、3000
(应用服务器)或 5555
(Prisma Studio 服务器)。
¥Before starting, ensure that no PostgreSQL services are running locally, and that the following ports are free to avoid conflicts: 5432
(PostgreSQL), 3000
(application server) or 5555
(Prisma Studio server).
要停止现有的 PostgreSQL 服务,请使用:
¥To stop existing PostgreSQL services, use:
sudo systemctl stop postgresql # Linux
brew services stop postgresql # macOS
net stop postgresql # Windows (Run as Administrator)
要停止所有正在运行的 Docker 容器并释放端口:
¥To stop all running Docker containers and free up ports:
docker ps -q | xargs docker stop
1. 设置 Node.js 和 Prisma 应用
¥ Set up your Node.js and Prisma application
让我们首先使用 Prisma ORM 和 Express.js 创建一个简单的 Node.js 应用。
¥Let's start by creating a simple Node.js application with Prisma ORM and Express.js.
1.1.初始化你的项目
¥1.1. Initialize your project
首先,创建一个新的项目目录并初始化一个 Node.js 项目:
¥First, create a new project directory and initialize a Node.js project:
mkdir docker-test
cd docker-test
npm init -y
这将生成一个 package.json
文件:
¥This will generate a package.json
file:
{
"name": "docker-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {},
"keywords": [],
"author": "",
"license": "ISC"
}
1.2.安装所需依赖
¥1.2. Install required dependencies
接下来,安装 Prisma CLI 作为开发依赖,并为服务器安装 Express.js:
¥Next, install the Prisma CLI as a development dependency and Express.js for the server:
npm install prisma --save-dev && npm install @prisma/client
npm install express
1.3.设置 Prisma ORM
¥1.3. Set up Prisma ORM
现在,初始化 Prisma 以生成必要的文件:
¥Now, initialize Prisma to generate the necessary files:
npx prisma init --output ../generated/prisma
这创建:
¥This creates:
-
一个包含
schema.prisma
的prisma
文件夹,你将在其中定义数据库模式。¥A
prisma
folder containingschema.prisma
, where you will define your database schema. -
项目根目录中的
.env
文件,用于存储环境变量。¥An
.env
file in the project root, which stores environment variables.
将 User
模型添加到位于 prisma/schema.prisma
文件夹中的 schema.prisma
文件中:
¥Add a User
model to the schema.prisma
file located in the prisma/schema.prisma
folder:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
output = "../generated/prisma_client"
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
email String @unique
name String?
}
在 schema.prisma
文件中,我们指定 Prisma 将在其中生成其类型的 自定义 output
路径 文件。这确保了 Prisma 的类型在不同的包管理器之间得到正确解析,并且应用可以在容器内一致地访问这些类型,而不会出现任何权限问题。在本指南中,类型将在 ./generated/prisma_client
目录中生成。
¥In the schema.prisma
file, we specify a custom output
path where Prisma will generate its types. This ensures Prisma's types are resolved correctly across different package managers and can be accessed by application consistently inside the container without any permission issues. In this guide, the types will be generated in the ./generated/prisma_client
directory.
1.4.创建一个 Express.js 服务器
¥1.4. Create an Express.js server
有了 Prisma 模式,让我们创建一个 Express.js 服务器来与数据库交互。首先创建一个 index.js
文件:
¥With the Prisma schema in place, let's create an Express.js server to interact with the database. Start by creating an index.js
file:
touch index.js
添加以下代码以设置基本的 Express 服务器:
¥Add the following code to set up a basic Express server:
const express = require("express");
const { PrismaClient } = require("./generated/prisma_client");
const app = express();
const prisma = new PrismaClient();
app.use(express.json());
// Get all users
app.get("/", async (req, res) => {
const userCount = await prisma.user.count();
res.json(
userCount == 0
? "No users have been added yet."
: "Some users have been added to the database."
);
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
更新 package.json
脚本以包含用于运行服务器和部署迁移的命令:
¥Update the package.json
scripts to include commands for running the server and deploying migrations:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node index.js",
"db:deploy": "npx prisma migrate deploy && npx prisma generate"
}
现在应用已设置完毕,让我们继续使用 Docker Compose 配置 PostgreSQL 数据库。
¥Now that the application is set up, let's move on to configuring a PostgreSQL database using Docker Compose.
2. 使用 Docker Compose 设置 PostgreSQL 数据库
¥ Set up a PostgreSQL database with Docker Compose
要执行数据库迁移,我们将使用 Docker Compose 创建一个独立的 PostgreSQL 数据库。
¥To perform database migrations, we'll create a standalone PostgreSQL database using Docker Compose.
2.1.为 PostgreSQL 创建 Docker Compose 文件
¥2.1. Create a Docker Compose file for PostgreSQL
在根目录中创建一个 docker-compose.postgres.yml
文件:
¥Create a docker-compose.postgres.yml
file in the root directory:
version: '3.7'
services:
postgres:
image: postgres:15
restart: always
environment:
- POSTGRES_DB=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=prisma
ports:
- "5432:5432"
networks:
- prisma-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U prisma -d postgres"]
interval: 5s
timeout: 2s
retries: 20
volumes:
- postgres_data:/var/lib/postgresql/data
command: postgres -c listen_addresses='*'
logging:
options:
max-size: "10m"
max-file: "3"
networks:
prisma-network:
volumes:
postgres_data:
2.2.启动 PostgreSQL 容器
¥2.2. Start the PostgreSQL container
运行以下命令,启动数据库:
¥Run the following command to start the database:
docker compose -f docker-compose.postgres.yml up -d
2.3.执行数据库迁移
¥2.3. Perform database migrations
数据库运行时,使用以下数据库连接 URL 更新 .env
文件:
¥With the database running, update the .env
file with the following database connection url:
DATABASE_URL="postgresql://postgres:prisma@localhost:5432/postgres?schema=public"
运行迁移,创建数据库模式:
¥Run the migration to create the database schema:
npx prisma migrate dev --name init
这将在 prisma
文件夹中生成一个 migrations
文件夹。
¥This should generate a migrations
folder in the prisma
folder.
2.4.测试应用
¥2.4. Test the application
启动服务器并验证其正常运行:
¥Start the server and verify it works:
npm run dev
访问 http://localhost:3000
查看消息:
¥Visit http://localhost:3000
to see the message:
No users have been added yet.
停止本地服务器。
¥Stop the local server.
2.5.清理独立数据库
¥2.5. Clean up the standalone database
测试完成后,移除独立的 PostgreSQL 容器:
¥Once testing is complete, remove the standalone PostgreSQL container:
docker compose -f docker-compose.postgres.yml down --remove-orphans
该命令将:
¥This command will:
-
停止正在运行的容器。
¥Stop running containers.
-
移除容器。
¥Remove containers.
-
移除 Docker Compose 创建的默认网络。
¥Remove the default network created by Docker Compose.
-
移除关联的卷(如果未明确指定)。
¥Remove associated volumes (if not named explicitly).
现在我们已经在本地测试了应用,让我们使用 Docker 对其进行容器化。
¥Now that we've tested the application locally, let's containerize it using Docker.
3. 使用 Docker Compose 运行应用和数据库
¥ Run the app and database together with Docker Compose
我们现在将使用 Docker 对应用进行容器化,以确保它可以在任何环境中运行。
¥We'll now containerize the application using Docker, ensuring it can run in any environment.
为此,请在项目根目录中创建一个 Dockerfile
:
¥To do that create a Dockerfile
in project root:
touch Dockerfile
下一步,你需要在基础镜像的两个选项之间进行选择:node:alpine
(轻量级)或 node:slim
(稳定版)。Prisma ORM 完全支持这两种选项,但可能需要进行不同的配置。
¥For the next step, you'll need to choose between two options for the base image: node:alpine
(lightweight) or node:slim
(stable). Both options are fully supported by Prisma ORM, but may have to be configured differently.
3.1.选项 1:使用 Linux 使用 Alpine (node:alpine
) 作为基础镜像
¥3.1. Option 1: Use Linux Alpine (node:alpine
) as a base image
node:alpine 镜像基于 Alpine Linux,这是一个使用 musl
C 标准库的轻量级 Linux 发行版。如果你想保持容器小巧高效,它是完美的选择。Prisma 在 amd64
上开箱即用地支持 Alpine,并从 prisma@4.10.0
开始在 arm64
上也支持 Alpine。
¥The node:alpine image is based on Alpine Linux, a lightweight Linux distribution that uses the musl
C standard library. It's perfect if you want to keep your container small and efficient. Prisma supports Alpine on amd64
out of the box, and supports it on arm64
since prisma@4.10.0
.
将以下内容添加到 Dockerfile
文件:
¥Add the following content to the Dockerfile
:
FROM node:lts-alpine3.17
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["sh", "-c", "npm run db:deploy && npm run dev"]
在 Linux Alpine 上运行时,Prisma 会下载针对 musl
C 标准库编译的引擎。请勿在 Alpine 上安装 glibc
(例如,通过 libc6-compat
软件包),因为这会导致 Prisma 无法成功运行。
¥When running on Linux Alpine, Prisma downloads engines that are compiled for the musl
C standard library. Please don't install glibc
on Alpine (e.g., via the libc6-compat
package), as that would prevent Prisma from running successfully.
相关 Docker 镜像:
¥Related Docker images:
-
node:lts-alpine
-
node:16-alpine
-
node:14-alpine
3.1.选项 2:使用 Linux Debian (node:slim
) 作为基础镜像
¥3.1. Option 2: Use Linux Debian (node:slim
) as a base image
node:slim
镜像基于 Linux Debian,这是一个稳定且受到广泛支持的发行版,它使用 glibc
C 标准库。它在 amd64
和 arm64
上基本开箱即用,如果你遇到与 Alpine 的兼容性问题或需要更适合生产环境的环境,它是一个不错的选择。但是,此镜像的某些旧版本可能未安装 libssl
,因此有时需要手动安装。
¥The node:slim
image is based on Linux Debian, a stable and widely supported distribution that uses the glibc
C standard library. It is mostly supported out of the box on amd64
and arm64
, making it a good choice if you're running into compatibility issues with Alpine or need a more production-ready environment. However, some older versions of this image may come without libssl
installed, so it's sometimes necessary to install it manually.
将以下内容添加到 Dockerfile
文件:
¥Add the following content to the Dockerfile
:
FROM node:slim
RUN apt-get update -y \
&& apt-get install -y openssl
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
COPY . .
RUN npm ci
CMD ["sh", "-c", "npm run db:deploy && npm run dev"]
相关 Docker 镜像:
¥Related Docker images:
-
node:lts-slim
-
node:bullseye-slim
-
node:buster-slim
-
node:stretch-slim
3.2.创建并配置 Docker Compose 文件
¥3.2. Create and configure a Docker Compose file
Dockerfile
已准备就绪,我们将使用 Docker Compose 来同时管理应用和数据库。这可以轻松启动、停止和管理整个设置。
¥Now that the Dockerfile
is ready, we'll use Docker Compose to manage both the app and the database together. This makes it easy to start, stop, and manage the entire setup.
在你的项目文件夹中创建一个 docker-compose.yml
文件:
¥Create a docker-compose.yml
file in your project folder:
touch docker-compose.yml
将以下配置添加到文件:
¥Add the following configuration to the file:
version: '3.7'
services:
postgres_db:
image: postgres:15
hostname: postgres_db
container_name: postgres_db
restart: always
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: prisma
ports:
- '5432:5432'
networks:
- prisma-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]
interval: 5s
timeout: 2s
retries: 20
server:
build:
context: .
dockerfile: Dockerfile
ports:
- '3000:3000'
stdin_open: true
tty: true # Keeps the container running for debugging
depends_on:
postgres_db:
condition: service_healthy
env_file:
- .env.prod
networks:
- prisma-network
networks:
prisma-network:
name: prisma-network
3.3.配置容器的环境变量
¥3.3. Configure environment variable for the container
在运行应用之前,我们需要配置环境变量。创建 .env.prod
文件:
¥Before running the app, we need to configure the environment variables. Create a .env.prod
file:
touch .env.prod
将以下数据库连接 URL 添加到 .env.prod
文件:
¥Add the following database connection url to the .env.prod
file:
DATABASE_URL="postgresql://postgres:prisma@postgres_db:5432/postgres?schema=public"
3.4.构建并运行应用
¥3.4. Build and run the application
一切设置完成后,就可以使用 Docker Compose 构建和运行应用了。运行以下命令:
¥With everything set up, it's time to build and run the app using Docker Compose. Run the following command:
docker compose -f docker-compose.yml up --build -d
访问 http://localhost:3000
查看你的应用运行时显示的消息:
¥Visit http://localhost:3000
to see your app running with the message:
No users have been added yet.
3.5.奖金:添加 Prisma Studio 用于数据库管理
¥3.5. Bonus: Add Prisma Studio for database management
Prisma 工作室 提供图形用户界面 (GUI),允许你直接在浏览器中查看和管理数据库。它是在开发过程中调试和管理数据的绝佳工具。
¥Prisma Studio offers a graphical user interface (GUI) that allows you to view and manage your database directly in the browser. It's a great tool for debugging and managing your data during development.
要将 Prisma Studio 添加到你的 Docker 设置中,请更新 docker-compose.yml
文件:
¥To add Prisma Studio to your Docker setup, update the docker-compose.yml
file:
version: '3.7'
services:
postgres_db:
image: postgres:15
hostname: postgres_db
container_name: postgres_db
restart: always
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: prisma
ports:
- '5432:5432'
networks:
- prisma-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]
interval: 5s
timeout: 2s
retries: 20
server:
build:
context: .
dockerfile: Dockerfile
ports:
- '3000:3000'
stdin_open: true
tty: true # Keeps the container running for debugging
depends_on:
postgres_db:
condition: service_healthy
env_file:
- .env.prod
networks:
- prisma-network
prisma-studio:
image: node:lts-alpine3.17
working_dir: /usr/src/app
volumes:
- .:/usr/src/app
command: npx prisma studio --port 5555 --browser none
ports:
- "5555:5555"
env_file:
- .env.prod
networks:
- prisma-network
depends_on:
postgres_db:
condition: service_healthy
server:
condition: service_started
networks:
prisma-network:
name: prisma-network
这将在 http://localhost:5555
启动 Prisma Studio,并在 http://localhost:3000
启动主应用。你可以使用 Prisma Studio 通过 GUI 管理数据库。
¥This will start Prisma Studio at http://localhost:5555
alongside the main app at http://localhost:3000
. You can use Prisma Studio to manage your database with a GUI.
运行以下命令,启动所有程序:
¥Run the following command to start everything:
docker compose -f docker-compose.yml up --build -d
按照本指南操作,你已成功使用 Docker Compose 将 Prisma 应用和数据库容器化。
¥By following this guide, you've successfully containerized your Prisma app and database using Docker Compose.
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.