Merge pull request #13 from ANONYMOUSZED-beep/chore/production-deployment-lite

Harden production deployment lifecycle
This commit is contained in:
lezi authored and GitHub committed 2026-08-14 13:19:29 +08:00
commit 547742cb6d
12 files changed
+485 -35

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
.git
.github
.env
.env.*
!.env.example
node_modules
npm-debug.log*
uploads
coverage
*.md
+4
View File
@@ -0,0 +1,4 @@
# Copy to .env, then set both required secrets before running Docker Compose.
POSTGRES_PASSWORD=
JWT_SECRET=
PORT=3000
+19
View File
@@ -0,0 +1,19 @@
FROM node:22.23.2-bookworm-slim
ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --chown=node:node . .
RUN mkdir -p /app/uploads && chown node:node /app/uploads
RUN chmod +x /app/scripts/docker-entrypoint.sh
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD ["node", "scripts/healthcheck.js"]
ENTRYPOINT ["/app/scripts/docker-entrypoint.sh"]
+40 -5
View File
@@ -39,8 +39,11 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
```
git clone https://github.com/forumlify/public.git
cd forumlify
printf 'JWT_SECRET=%s\n' "$(openssl rand -hex 32)" > .env
docker compose up -d
cp .env.example .env
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
docker compose up --build -d
```
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
@@ -48,6 +51,33 @@ docker compose up -d
应用默认运行在 `http://localhost:3000`。
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
```bash
docker compose ps
docker compose logs -f app
curl http://localhost:3000/health/live
curl http://localhost:3000/health/ready
```
- `/health/live` 表示 Node.js 服务正在运行。
- `/health/ready` 仅在 PostgreSQL 可用时返回成功。
- PostgreSQL 不再暴露到宿主机网络;应用通过 Compose 内部网络访问数据库。
- 应用收到 `SIGTERM`/`SIGINT` 后会停止接收新连接并关闭数据库连接池。
升级代码后执行 `docker compose up --build -d`,应用会在启动前自动应用新增迁移。
#### Docker 数据备份
数据库保存在 `db_data` 卷中,上传文件继续保存在宿主机的 `./uploads` 目录,以兼容旧版部署。升级或删除容器前请备份:
```bash
docker compose exec -T db pg_dump -U forumlify forumlify > forumlify.sql
tar czf forumlify-uploads.tar.gz uploads/
```
`docker compose down` 会保留数据卷;只有明确执行 `docker compose down -v` 才会删除数据。
---
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
@@ -81,20 +111,25 @@ psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
psql -U forumlify -d forumlify -f schema.sql
```
3. **配置环境变量**(可选)
3. **配置环境变量**
| 变量 | 默认值 | 说明 |
|------|--------|------|
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
| `PORT` | `3000` | HTTP 监听端口 |
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 |
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
4. **启动**
4. **执行迁移并启动**
```bash
npm run migrate
npm start
```
+34 -15
View File
@@ -1,35 +1,54 @@
version: '3'
services:
db:
image: postgres:15
image: postgres:15.14-alpine
restart: unless-stopped
environment:
POSTGRES_USER: forumlify
POSTGRES_PASSWORD: 123456
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
POSTGRES_DB: forumlify
volumes:
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
- db_data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U forumlify -d forumlify"]
interval: 5s
timeout: 5s
retries: 10
start_period: 10s
app:
# 从 GHCR 拉取镜像(每次 push Lite 自动重建),不再本地构建
image: ghcr.io/furrium/forumlify:lite
build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
ports:
- "3000:3000"
- "${PORT:-3000}:3000"
depends_on:
- db
db:
condition: service_healthy
environment:
DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify
NODE_ENV: production
PORT: 3000
PGHOST: db
PGPORT: 5432
PGUSER: forumlify
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
PGDATABASE: forumlify
JWT_SECRET: ${JWT_SECRET:?Set JWT_SECRET in .env}
ADMIN_BOOTSTRAP_TOKEN: ${ADMIN_BOOTSTRAP_TOKEN:-}
ENABLE_CAPTCHA: "true"
JWT_SECRET: "${JWT_SECRET:?Set JWT_SECRET in .env before starting Forumlify}"
# 信任反向代理(Nginx / Docker 端口转发),修复限流警告
TRUST_PROXY: "true"
volumes:
- ./uploads:/app/uploads
restart: unless-stopped
healthcheck:
test: ["CMD", "node", "scripts/healthcheck.js"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
volumes:
db_data:
-7
View File
@@ -1,7 +0,0 @@
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
+209
View File
@@ -0,0 +1,209 @@
-- ============================================================
-- Forumlify 数据库表结构
-- ============================================================
-- 用户表
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
username VARCHAR(20) UNIQUE NOT NULL,
avatar_url TEXT,
bio TEXT DEFAULT '',
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
created_at TIMESTAMPTZ DEFAULT now()
);
-- 帖子表
CREATE TABLE IF NOT EXISTS posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
images TEXT[] DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- 回复表
CREATE TABLE IF NOT EXISTS replies (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- 友情链接表
CREATE TABLE IF NOT EXISTS friendly_links (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(100) NOT NULL,
url TEXT NOT NULL,
sort_order INT DEFAULT 0
);
-- 举报表
CREATE TABLE IF NOT EXISTS reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
reason VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
created_at TIMESTAMPTZ DEFAULT now(),
handled_at TIMESTAMPTZ,
handler_id UUID REFERENCES users(id) ON DELETE SET NULL,
handler_note TEXT
);
-- Preserve moderation history when a reported post is deleted. This also
-- upgrades databases created with the previous ON DELETE CASCADE constraint.
DO $$
DECLARE
constraint_name TEXT;
BEGIN
SELECT con.conname INTO constraint_name
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey)
WHERE rel.relname = 'reports'
AND con.contype = 'f'
AND attr.attname = 'post_id'
LIMIT 1;
IF constraint_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name);
END IF;
ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL;
ALTER TABLE reports
ADD CONSTRAINT reports_post_id_fkey
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL;
END $$;
-- 事件日志表
CREATE TABLE IF NOT EXISTS event_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
action VARCHAR(50) NOT NULL,
ip VARCHAR(45),
created_at TIMESTAMPTZ DEFAULT now()
);
-- ============================================================
-- 论坛设置表
-- ============================================================
CREATE TABLE IF NOT EXISTS settings (
key VARCHAR(50) PRIMARY KEY,
value TEXT NOT NULL,
updated_at TIMESTAMPTZ DEFAULT now()
);
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
ON CONFLICT (key) DO NOTHING;
-- ============================================================
-- 私信系统
-- ============================================================
-- 私信会话表
CREATE TABLE IF NOT EXISTS conversations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
last_message_at TIMESTAMPTZ DEFAULT now(),
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(user1_id, user2_id)
);
-- 私信消息表
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id);
CREATE INDEX IF NOT EXISTS idx_messages_sender_id ON messages(sender_id);
CREATE INDEX IF NOT EXISTS idx_conversations_user1_id ON conversations(user1_id);
CREATE INDEX IF NOT EXISTS idx_conversations_user2_id ON conversations(user2_id);
-- ============================================================
-- 自定义页面表
-- ============================================================
CREATE TABLE IF NOT EXISTS custom_pages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(50) NOT NULL UNIQUE,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
enabled BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name);
-- ============================================================
-- 通知系统
-- ============================================================
CREATE TABLE IF NOT EXISTS notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(30) NOT NULL,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
link TEXT,
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id);
CREATE INDEX IF NOT EXISTS idx_notifications_is_read ON notifications(is_read);
-- ============================================================
-- 自动更新 updated_at 的触发器
-- ============================================================
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS update_posts_updated_at ON posts;
CREATE TRIGGER update_posts_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
ALTER TABLE posts ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ;
-- ============================================================
-- 恢复码表(密码重置用)
-- ============================================================
CREATE TABLE IF NOT EXISTS recovery_codes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash VARCHAR(255) NOT NULL,
is_used BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id);
-- 帖子表添加置顶字段
ALTER TABLE posts ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN DEFAULT false;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
-- 创建索引
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
-- ============================================================
-- 论坛默认设置
-- ============================================================
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
ON CONFLICT (key) DO NOTHING;
+2
View File
@@ -9,8 +9,10 @@
"scripts": {
"start": "node server.js",
"dev": "node server.js",
"migrate": "node scripts/migrate.js",
"check": "node scripts/check-syntax.js",
"test": "node --test"
},
"dependencies": {
"bcryptjs": "3.0.3",
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
node scripts/migrate.js
exec node server.js
+11
View File
@@ -0,0 +1,11 @@
const port = process.env.PORT || 3000;
const url = `http://127.0.0.1:${port}/health/ready`;
fetch(url, { signal: AbortSignal.timeout(4000) })
.then(response => {
if (!response.ok) throw new Error(`readiness returned ${response.status}`);
})
.catch(error => {
console.error(error.message);
process.exit(1);
});
+59
View File
@@ -0,0 +1,59 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { Pool } = require('pg');
const migrationsDir = path.join(__dirname, '..', 'migrations');
if (!process.env.DATABASE_URL && !process.env.PGHOST) {
console.error('DATABASE_URL or PGHOST is required to run migrations.');
process.exit(1);
}
async function migrate() {
const pool = new Pool();
const client = await pool.connect();
try {
await client.query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
const files = (await fs.readdir(migrationsDir))
.filter(file => /^\d+.*\.sql$/.test(file))
.sort();
const applied = await client.query('SELECT filename FROM schema_migrations');
const appliedFiles = new Set(applied.rows.map(row => row.filename));
for (const filename of files) {
if (appliedFiles.has(filename)) continue;
const sql = await fs.readFile(path.join(migrationsDir, filename), 'utf8');
console.log(`Applying migration ${filename}`);
await client.query('BEGIN');
try {
await client.query(sql);
await client.query(
'INSERT INTO schema_migrations (filename) VALUES ($1)',
[filename]
);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}
console.log('Database migrations are up to date.');
} finally {
client.release();
await pool.end();
}
}
migrate().catch(error => {
console.error('Database migration failed:', error);
process.exit(1);
});
+92 -8
View File
@@ -25,16 +25,30 @@ const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000;
const DEFAULT_JWT_SECRET = 'forumlify-secret-key-change-me-in-production';
const JWT_SECRET = process.env.JWT_SECRET || DEFAULT_JWT_SECRET;
if (process.env.NODE_ENV === 'production' && JWT_SECRET === DEFAULT_JWT_SECRET) {
throw new Error('JWT_SECRET must be set to a unique value in production');
if (process.env.NODE_ENV === 'production') {
if (JWT_SECRET === DEFAULT_JWT_SECRET) {
throw new Error('JWT_SECRET must be set to a unique value in production');
}
if (JWT_SECRET.length < 32) {
console.warn('Warning: JWT_SECRET should contain at least 32 characters; rotate it during a planned session reset.');
}
if (!process.env.DATABASE_URL && !process.env.PGHOST) {
throw new Error('DATABASE_URL or PGHOST must be configured in production');
}
}
// ============================================================
// 数据库
// ============================================================
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5432/forumlify',
});
const pool = new Pool(process.env.DATABASE_URL
? { connectionString: process.env.DATABASE_URL }
: {
host: process.env.PGHOST || 'localhost',
port: Number(process.env.PGPORT || 5432),
user: process.env.PGUSER || 'forumlify',
password: process.env.PGPASSWORD || '123456',
database: process.env.PGDATABASE || 'forumlify',
});
// ============================================================
// 中间件
@@ -1669,6 +1683,19 @@ app.post('/api/auth/reset-password', async (req, res) => {
// 托管公开前端文件
// ============================================================
app.get('/health/live', (req, res) => {
res.json({ status: 'ok' });
});
app.get('/health/ready', async (req, res) => {
try {
await pool.query('SELECT 1');
res.json({ status: 'ready' });
} catch (error) {
res.status(503).json({ status: 'not_ready' });
}
});
app.use('/js', express.static(path.join(__dirname, 'js'), {
dotfiles: 'deny',
fallthrough: false,
@@ -1707,14 +1734,71 @@ app.use((err, req, res, next) => {
// 启动服务器
// ============================================================
if (require.main === module) {
app.listen(PORT, '0.0.0.0', () => {
let server = null;
let shuttingDown = false;
function startServer() {
if (server) return server;
server = app.listen(PORT, '0.0.0.0', () => {
console.log('========================================');
console.log(' 🌊 Forumlify 已启动');
console.log(' 📡 http://localhost:' + PORT);
console.log(' 📡 API: http://localhost:' + PORT + '/api');
console.log('========================================');
});
return server;
}
module.exports = { app, pool };
function shutdown(signal, { exitProcess = true } = {}) {
if (shuttingDown) return Promise.resolve();
shuttingDown = true;
console.log(`${signal} received, shutting down gracefully`);
return new Promise((resolve, reject) => {
const forceExit = exitProcess
? setTimeout(() => process.exit(1), 10000)
: null;
if (forceExit) forceExit.unref();
const finish = async error => {
try {
await pool.end();
if (error) throw error;
resolve();
} catch (shutdownError) {
reject(shutdownError);
} finally {
if (forceExit) clearTimeout(forceExit);
server = null;
shuttingDown = false;
}
};
if (server) server.close(finish);
else finish();
}).finally(() => {
if (exitProcess) process.exitCode = 0;
});
}
if (require.main === module) {
startServer();
process.on('SIGTERM', () => {
shutdown('SIGTERM').catch(error => {
console.error('Graceful shutdown failed:', error);
process.exitCode = 1;
});
});
process.on('SIGINT', () => {
shutdown('SIGINT').catch(error => {
console.error('Graceful shutdown failed:', error);
process.exitCode = 1;
});
});
}
module.exports = { app, pool, startServer, shutdown };