本文不做詳細解釋。相反,我將只提供對 PERN 堆疊應用程式進行 docker 化所需的程式碼片段。如果您想要更詳細的解釋,請查看這篇文章,我更深入地介紹了所有內容。
pern-project/ --- frontend/ ------ .dockerignore ------ frontend.dockerfile ------ ... --- backend/ ------ .dockerignore ------ backend.dockerfile ------ ... --- docker-compose.yml
先建立一個node.js-express.js應用程式:
mkdir backend && cd backend npm init -y
從 npm 安裝所有必需的依賴項:
npm install express dotenv cors
同時安裝 Typescript 相關的開發依賴項:
npm install --save-dev typescript ts-node @types/express @types/node @types/cors
產生 tsconfig.json 檔案:
tsc --init
將 tsconfig.json 中的所有內容替換為以下程式碼:
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "rootDir": "./src", "outDir": "./dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": ["src/**/*.ts", "data-types.d.ts"] }
在 src 資料夾中建立 src 資料夾和 index.ts 檔案。所以,現在後端資料夾結構:
backend/ --- node_modules/ --- src/ ------ index.ts --- package.json --- tsconfig.json --- ...
先安裝 Prisma 和 Prisma 用戶端:
npm i @prisma/client npm i --save-dev prisma
產生 prisma 資料夾:
npx prisma init
在 schema.prisma 檔案中寫入使用者模型:
generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id String @id @default(uuid()) name String username String email String password String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@map("users") }
在 .env 檔案中設定 DATABASE_URL:
DATABASE_URL=postgresql://postgres:postgres@db:5432/pern_db?schema=public
在 src 資料夾中建立檔案 prismadb.ts:
import { PrismaClient } from "@prisma/client" import "dotenv/config" // Extend the global object with PrismaClient declare global { var prisma: PrismaClient | undefined } // Prevent multiple instances of Prisma Client in development const prisma = global.prisma || new PrismaClient() if (process.env.NODE_ENV !== "production") global.prisma = prisma export default prisma
在index.ts檔中定義/register端點。 index.ts 文件:
import express, { Request, Response } from "express" import "dotenv/config" import cors from "cors" import { corsOptions } from "./constants/config" const app = express() const PORT = process.env.PORT || 3000 app.use(express.json()) app.use(express.urlencoded({ extended: true })) app.use(cors({ const corsOptions = { origin: process.env.CLIENT_URL || 'http://localhost:5173', credentials: true, } })) app.get("/", (req: Request, res: Response) => { res.json({ message: "Hello, TypeScript with Express! Updated!", }) }) app.post("/register", async (req: Request, res: Response) => { const { name, username, email, password } = req.body await prisma.user.create({ data: { name, username, email, password, }, }) res.json({ message: "User created successfully", }) }) app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`) })
在後端目錄的根目錄下建立一個名為 backend.dockerfile 的文件,並寫入:
FROM node:20 WORKDIR /app COPY package*.json . RUN npm install COPY prisma ./prisma RUN npx prisma generate COPY . . EXPOSE 3000 RUN npm install -g nodemon ts-node CMD ["nodemon", "src/index.ts"]
要排除 node_modules,請建立一個 .dockerignore 檔案:
node_modules
建立前端:
npm create vite@latest frontend -- --template react-ts
在 React 應用程式中進行 API 呼叫:
// App.tsx import { FormEvent, useEffect, useState } from "react" .... function App() { const [name, setName] = useState("") const [username, setUsername] = useState("") const [email, setEmail] = useState("") const [password, setPassword] = useState("") const saveUser = async (e: FormEvent) => { e.preventDefault() await fetch("http://localhost:3000/register", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name, username, email, password, }), }) .then((res) => res.json()) .then((data) => console.log(data)) } useEffect(() => { fetch("http://localhost:3000") .then((res) => res.json()) .then((data) => console.log(data)) }, []) return ( <> <form onSubmit={saveUser}> <input type="text" onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> <input type="text" onChange={(e) => setUsername(e.target.value)} placeholder="Enter your username" /> <input type="email" onChange={(e) => setEmail(e.target.value)} placeholder="Enter your email" /> <input type="password" onChange={(e) => setPassword(e.target.value)} placeholder="Enter your password" /> <button type="submit">Submit</button> </form> </> ) } export default App
在前端目錄的根目錄中建立一個名為 frontend.dockerfile 的文件,並寫入:
FROM node:20 WORKDIR /app COPY package*.json . RUN npm install EXPOSE 5173 COPY . . CMD [ "npm", "run", "dev" ]
在後端資料夾的.env檔案中加入以下內容:
// backend/.env POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=pern_db DATABASE_URL=postgresql://postgres:postgres@db:5432/pern_db?schema=public
docker-compose.yml 檔案:
services: frontend: container_name: frontend build: context: ./frontend dockerfile: frontend.dockerfile ports: - "5173:5173" networks: - pern_net volumes: - ./frontend:/app - /app/node_modules depends_on: - server backend: container_name: backend build: context: ./backend dockerfile: backend.dockerfile env_file: - ./backend/.env ports: - "3000:3000" networks: - pern_net volumes: - ./backend:/app - /app/node_modules depends_on: - db db: container_name: db image: postgres:14 restart: always ports: - "5432:5432" networks: - pern_net env_file: - ./backend/.env volumes: - pgdata:/data/db networks: pern_net: driver: bridge volumes: pgdata: {}
執行此指令:
docker compose up -d
遷移 prisma 架構:
docker backend -it backend npx prisma migrate dev --name init
以上是使用 Prisma ORM 和 Docker Compose 來 Dockerize PERN-TypeScript 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!