Docker化部署:多阶段构建 + docker-compose 编排;删除开发/内置服务器脚本;安全加固

This commit is contained in:
Fei-Qing committed 2026-06-24 19:22:26 +08:00
1 parent 044e526c80
commit af98618810
15 files changed
+424 -127

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
# Git
.git/
.gitignore
.gitattributes
# 文档
*.md
!README.md
# IDE
.idea/
.vscode/
*.swp
*.swo
# Node
node_modules/
frontend/node_modules/
frontend/dist/
# PHP
vendor/
backend/vendor/
backend/.env
backend/storage/cache/*
backend/storage/logs/*
backend/tests/
backend/tmp_*.php
backend/composer.lock
# Docker
docker-compose.yml
.dockerignore
.env.docker
deploy.sh
# OS
.DS_Store
Thumbs.db
*.log
+21
View File
@@ -0,0 +1,21 @@
# Docker Compose 环境变量
# 复制为 .env 并按需修改
# 访问地址
APP_URL=http://localhost:8080
# 数据库
MYSQL_ROOT_PASSWORD=root_secret_change_me
DB_NAME=card_auth
DB_USER=card_auth
DB_PASS=card_auth_pass
# JWT 密钥(留空则自动生成随机密钥,但容器重启会变)
# 生成方式: openssl rand -base64 48
JWT_SECRET=
# 支付(可选)
PAYMENT_TYPE=epay
PAYMENT_API_URL=
PAYMENT_APP_ID=
PAYMENT_APP_KEY=
+3
View File
@@ -2,7 +2,10 @@
# 后端
/backend/.env
/.env
/backend/storage/cache/*
/backend/storage/logs/*
!/backend/storage/logs/.gitkeep
/backend/vendor/
# 前端
+59
View File
@@ -0,0 +1,59 @@
# ============================================
# CardAuth Docker - Multi-stage Build
# ============================================
# Stage 1: 前端构建
FROM node:18-alpine AS frontend-builder
WORKDIR /app/frontend
COPY frontend/package*.json ./
RUN npm ci --registry=https://registry.npmmirror.com
COPY frontend/ ./
RUN npm run build
# Stage 2: PHP 运行时
FROM php:8.1-fpm-alpine
# 安装系统依赖 & PHP 扩展
RUN set -ex \
&& apk add --no-cache \
nginx \
supervisor \
curl \
tzdata \
netcat-openbsd \
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& docker-php-ext-install -j$(nproc) pdo pdo_mysql bcmath
# Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
# 后端代码
WORKDIR /var/www
COPY backend/composer.json backend/composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-interaction --no-scripts
COPY backend/ ./
# 前端构建产物
COPY --from=frontend-builder /app/frontend/dist/ ./public/
# 权限
RUN set -ex \
&& mkdir -p storage/cache storage/logs \
&& chown -R www-data:www-data storage \
&& chmod -R 775 storage \
&& rm -rf tests .phpunit.cache
# Nginx 配置
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
# Supervisor 配置 (管理 Nginx + PHP-FPM)
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# 入口脚本
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
EXPOSE 80
ENTRYPOINT ["/entrypoint.sh"]
+103 -20
View File
@@ -40,43 +40,119 @@
## 快速开始
### 环境要求
- PHP 7.4+(需启用 PDO、PDO_MySQL)
- MySQL 8.0+
- Node.js 16+
### 方式一:Docker 部署(推荐)
### 1. 初始化数据库
```bash
# 1. 配置环境变量
cp .env.docker .env
# 编辑 .env,设置 JWT_SECRET 和数据库密码
# 2. 一键启动
docker compose up -d
# 3. 访问
http://localhost:8080
```
首次启动自动完成:前端构建 → 数据库初始化 → Nginx + PHP-FPM 启动。
### 方式二:传统部署
#### 环境要求
- Linux 服务器(CentOS 7+ / Ubuntu 18+ / Debian 10+)
- Nginx 1.18+
- PHP 8.1+(需启用 PDO、PDO_MySQL、mbstring、bcmath)
- PHP-FPM
- MySQL 8.0+
- Node.js 18+(仅构建阶段需要,部署后不需要)
- Composer
#### 1. 一键部署脚本
```bash
# 在项目根目录执行,按提示输入配置
sudo bash deploy.sh your-domain.com
```
脚本自动完成:环境检查 → 前端构建 → 文件部署 → 数据库初始化 → Nginx 配置 → 权限设置。
### 方式二:手动部署
#### 1. 初始化数据库
```bash
mysql -u root -p < backend/database/schema.sql
```
### 2. 配置后端
#### 2. 配置环境变量
```bash
cd backend
cp .env.example .env
# 编辑 .env 填入数据库信息
# 编辑 .env,确保:
# APP_ENV=production
# APP_DEBUG=false
# DB_* 填入实际数据库信息
# JWT_SECRET 填入随机 64 位字符串
```
### 3. 启动
#### 3. 安装依赖
```bash
# 一键启动(前端 + 后端)
.\start.ps1
# 或分别启动
cd backend && php -S 0.0.0.0:8080 -t backend
cd frontend && npm install && npm run dev
cd backend && composer install --no-dev --optimize-autoloader
cd ../frontend && npm install && npm run build
```
### 4. 访问
- 管理后台:`http://localhost:3000`
- 代理登录:`http://localhost:3000/#/agent/login`
- 购买商城:`http://localhost:3000/#/shop`
构建产物输出到 `frontend/dist/`,将其复制到 `backend/public/`:
```bash
cp -r frontend/dist/* backend/public/
```
### 5. 默认管理员
#### 4. 配置 Nginx
参考 [deploy/nginx.conf](deploy/nginx.conf),核心配置:
```nginx
server {
listen 443 ssl http2;
server_name your-domain.com;
root /www/wwwroot/your-site/public;
index index.php index.html;
# 前端 SPA fallback
location / {
try_files $uri $uri/ /index.html;
}
# API 路由到 PHP
location /api {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/tmp/php-cgi-74.sock; # 按实际 PHP 版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 安全加固
location ~ /\.(?!well-known) { deny all; }
location ~* \.(env|sql|log|md)$ { deny all; }
location ~* ^/(storage|config|routes)/ { deny all; }
}
```
#### 5. 设置权限
```bash
chown -R www:www /www/wwwroot/your-site
chmod -R 755 /www/wwwroot/your-site
chmod 600 /www/wwwroot/your-site/.env
```
#### 6. 默认管理员
| 用户名 | 密码 |
|--------|------|
| admin | admin123456 |
> 首次登录后请立即修改密码。
## SMTP 邮件通知配置
在系统配置 -> SMTP邮件配置中填写 SMTP 信息,系统将自动在授权到期前 N 天发送提醒邮件到联系人的 QQ 邮箱(`contact_qq@qq.com`)。
@@ -591,7 +667,14 @@ card/
│ ├── router/ # 路由配置
│ ├── stores/ # Pinia 状态管理
│ └── views/ # 页面组件 (管理后台 + 代理 + 公开)
└── deploy/ # 部署配置 (Nginx + 宝塔)
├── docker/ # Docker 配置
│ ├── nginx.conf # Nginx 容器配置
│ ├── supervisord.conf # Supervisor 进程管理
│ └── entrypoint.sh # 容器入口脚本
├── deploy/ # 传统部署配置 (Nginx + 宝塔)
├── Dockerfile # Docker 多阶段构建
├── docker-compose.yml # Docker 编排 (MySQL + App)
└── .env.docker # Docker 环境变量模板
```
## License
+3 -1
View File
@@ -1,4 +1,6 @@
APP_DEBUG=true
# 环境模式: development | production
APP_ENV=production
APP_DEBUG=false
APP_URL=http://your-domain.com
DB_HOST=127.0.0.1
+14 -4
View File
@@ -5,9 +5,19 @@
*/
// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', '0');
$isDev = (getenv('APP_ENV') ?: 'production') === 'development';
$isDebug = filter_var(getenv('APP_DEBUG') ?: 'false', FILTER_VALIDATE_BOOLEAN);
error_reporting($isDev ? E_ALL : E_ALL & ~E_DEPRECATED & ~E_STRICT);
ini_set('display_errors', $isDev ? '1' : '0');
ini_set('log_errors', '1');
ini_set('error_log', STORAGE_PATH . '/logs/error.log');
// 生产环境隐藏 PHP 版本
if (!$isDev) {
ini_set('expose_php', '0');
header_remove('X-Powered-By');
}
// 定义基础路径
define('BASE_PATH', dirname(__DIR__));
@@ -60,10 +70,10 @@ try {
http_response_code(500);
echo json_encode([
'code' => 500,
'message' => config('app.debug') ? $e->getMessage() : '服务器内部错误',
'message' => $isDebug ? $e->getMessage() : '服务器内部错误',
'data' => null,
], JSON_UNESCAPED_UNICODE);
if (config('app.debug')) {
if ($isDebug) {
error_log($e->getMessage() . "\n" . $e->getTraceAsString());
}
}
-44
View File
@@ -1,44 +0,0 @@
<?php
/**
* PHP内置服务器路由器
* 用法: php -S 0.0.0.0:8080 router.php
*/
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
// 静态文件直接返回
if ($uri !== '/' && file_exists(__DIR__ . '/public' . $uri)) {
$filePath = __DIR__ . '/public' . $uri;
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$mimeTypes = [
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
'png' => 'image/png', 'gif' => 'image/gif',
'webp' => 'image/webp', 'svg' => 'image/svg+xml',
'css' => 'text/css', 'js' => 'application/javascript',
'json' => 'application/json', 'ico' => 'image/x-icon',
];
header('Content-Type: ' . ($mimeTypes[$ext] ?? 'application/octet-stream'));
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: public, max-age=31536000');
readfile($filePath);
exit;
}
// API 请求走后端入口
if (str_starts_with($uri, '/api/')) {
require_once __DIR__ . '/public/index.php';
exit;
}
// 非 API 请求返回前端 SPA 入口(index.html),前端 Vue Router 负责渲染路由
$indexHtml = __DIR__ . '/public/index.html';
if (file_exists($indexHtml)) {
header('Content-Type: text/html; charset=utf-8');
readfile($indexHtml);
exit;
}
// 兜底:无法处理
http_response_code(404);
echo 'Not Found';
exit;
View File
Whitespace-only changes.
+59
View File
@@ -0,0 +1,59 @@
version: "3.8"
services:
db:
image: mysql:8.0
container_name: cardauth-db
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_secret_change_me}
MYSQL_DATABASE: ${DB_NAME:-card_auth}
MYSQL_USER: ${DB_USER:-card_auth}
MYSQL_PASSWORD: ${DB_PASS:-card_auth_pass}
volumes:
- mysql_data:/var/lib/mysql
- ./backend/database/schema.sql:/docker-entrypoint-initdb.d/01-schema.sql:ro
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
networks:
- cardauth
app:
build: .
container_name: cardauth-app
restart: unless-stopped
ports:
- "8080:80"
environment:
APP_ENV: production
APP_DEBUG: "false"
APP_URL: ${APP_URL:-http://localhost:8080}
DB_HOST: db
DB_PORT: "3306"
DB_NAME: ${DB_NAME:-card_auth}
DB_USER: ${DB_USER:-card_auth}
DB_PASS: ${DB_PASS:-card_auth_pass}
DB_PREFIX: ca_
JWT_SECRET: ${JWT_SECRET:-}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_secret_change_me}
PAYMENT_TYPE: ${PAYMENT_TYPE:-epay}
PAYMENT_API_URL: ${PAYMENT_API_URL:-}
PAYMENT_APP_ID: ${PAYMENT_APP_ID:-}
PAYMENT_APP_KEY: ${PAYMENT_APP_KEY:-}
depends_on:
db:
condition: service_healthy
networks:
- cardauth
volumes:
mysql_data:
driver: local
networks:
cardauth:
driver: bridge
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
set -e
# 从环境变量生成 .env
if [ ! -f /var/www/.env ]; then
echo ">>> Generating .env from environment..."
cat > /var/www/.env << EOF
APP_ENV=${APP_ENV:-production}
APP_DEBUG=${APP_DEBUG:-false}
APP_URL=${APP_URL:-http://localhost}
DB_HOST=${DB_HOST:-db}
DB_PORT=${DB_PORT:-3306}
DB_NAME=${DB_NAME:-card_auth}
DB_USER=${DB_USER:-card_auth}
DB_PASS=${DB_PASS:-}
DB_PREFIX=${DB_PREFIX:-ca_}
JWT_SECRET=${JWT_SECRET:-}
PAYMENT_TYPE=${PAYMENT_TYPE:-epay}
PAYMENT_API_URL=${PAYMENT_API_URL:-}
PAYMENT_APP_ID=${PAYMENT_APP_ID:-}
PAYMENT_APP_KEY=${PAYMENT_APP_KEY:-}
EOF
chmod 600 /var/www/.env
echo ">>> .env generated"
fi
# 等待 MySQL 就绪
echo ">>> Waiting for MySQL at ${DB_HOST}:${DB_PORT}..."
until nc -z ${DB_HOST} ${DB_PORT} 2>/dev/null; do
sleep 2
done
echo ">>> MySQL is ready"
# 启动 Supervisor (Nginx + PHP-FPM)
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
+53
View File
@@ -0,0 +1,53 @@
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /var/www/public;
index index.php index.html;
client_max_body_size 20M;
# 前端 SPA fallback
location / {
try_files $uri $uri/ /index.html;
}
# API 路由
location /api/ {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP-FPM
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_param HTTP_AUTHORIZATION $http_authorization;
fastcgi_hide_header X-Powered-By;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# 安全:禁止访问敏感文件
location ~ /\. {
deny all;
}
location ~* \.(env|sql|log|md|gitignore)$ {
deny all;
}
location ~* ^/(storage/cache|storage/logs)/ {
deny all;
}
# 禁止访问源代码目录
location ~* ^/(app|config|routes|database|vendor)/ {
deny all;
return 404;
}
}
+23
View File
@@ -0,0 +1,23 @@
[supervisord]
nodaemon=true
user=root
logfile=/dev/stdout
logfile_maxbytes=0
[program:php-fpm]
command=php-fpm -F
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:nginx]
command=nginx -g "daemon off;"
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
+8 -2
View File
@@ -5,7 +5,7 @@ import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
export default defineConfig(({ mode }) => ({
plugins: [
vue(),
AutoImport({ resolvers: [ElementPlusResolver()] }),
@@ -19,6 +19,8 @@ export default defineConfig({
server: {
host: '0.0.0.0',
port: 3000,
strictPort: false,
// 允许外部访问(开发模式下 nginx 反代需要,生产环境请用 npm run build)
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
@@ -34,5 +36,9 @@ export default defineConfig({
outDir: 'dist',
assetsDir: 'assets',
sourcemap: false,
// 生产构建时注入环境变量提示
define: mode === 'production' ? {} : {
__DEV_SERVER_WARNING__: JSON.stringify('当前为开发模式, 生产环境请使用 npm run build 构建后部署')
}
}
})
}))
-56
View File
@@ -1,56 +0,0 @@
# CardAuth One-Click Start Script
# Starts backend PHP server and frontend Vite dev server
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
$backendPath = Join-Path $projectRoot "backend"
$frontendPath = Join-Path $projectRoot "frontend"
function Test-PortInUse {
param([int]$Port)
$listener = $null
try {
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, $Port)
$listener.Start()
$listener.Stop()
return $false
} catch {
return $true
} finally {
if ($listener -ne $null) { $listener.Stop() }
}
}
function Start-Backend {
if (Test-PortInUse -Port 8080) {
Write-Host "[Backend] Port 8080 already in use, skip" -ForegroundColor Yellow
return
}
Write-Host "[Backend] Starting PHP server at http://127.0.0.1:8080 ..." -ForegroundColor Cyan
$proc = Start-Process -FilePath "php" -ArgumentList "-S 127.0.0.1:8080 router.php" -WorkingDirectory $backendPath -WindowStyle Hidden -PassThru
Write-Host "[Backend] Process ID: $($proc.Id)" -ForegroundColor Green
}
function Start-Frontend {
if (Test-PortInUse -Port 3000) {
Write-Host "[Frontend] Port 3000 already in use, skip" -ForegroundColor Yellow
return
}
Write-Host "[Frontend] Starting Vite dev server at http://localhost:3000 ..." -ForegroundColor Cyan
$proc = Start-Process -FilePath "cmd.exe" -ArgumentList "/c npm run dev" -WorkingDirectory $frontendPath -WindowStyle Hidden -PassThru
Write-Host "[Frontend] Process ID: $($proc.Id)" -ForegroundColor Green
}
Write-Host "============================================" -ForegroundColor Blue
Write-Host " CardAuth One-Click Start" -ForegroundColor Blue
Write-Host "============================================" -ForegroundColor Blue
Start-Backend
Start-Frontend
Write-Host ""
Write-Host "Services started. Please visit:" -ForegroundColor Green
Write-Host " Frontend: http://localhost:3000/" -ForegroundColor White
Write-Host " Admin: http://localhost:3000/#/login" -ForegroundColor White
Write-Host " Backend: http://127.0.0.1:8080" -ForegroundColor White
Write-Host ""
Write-Host "Note: background processes keep running after this window closes" -ForegroundColor Gray