feat: common-nginx-fpm-alpine

Signed-off-by: Caijinglong <cjl_spy@163.com>
This commit is contained in:
Caijinglong 2025-06-25 09:35:17 +08:00
commit e28c0de955
Signed by: cai
GPG Key ID: 92FBD82121AC80AA
13 changed files with 758 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# 项目上下文信息
- 创建了nginx+php-fpm通用Docker镜像提供Alpine和Debian两个版本。Alpine版本安全性更高(0漏洞 vs 152漏洞),推荐生产环境使用。包含完整的配置文件、安全扫描报告和使用文档。

View File

@ -0,0 +1,6 @@
{
"project_path": "/Users/cai/dockers/common-nginx-fpm",
"last_organized": "2025-06-25T01:31:54.805372Z",
"total_entries": 1,
"version": "1.0.0"
}

View File

@ -0,0 +1,2 @@
# 常用模式和最佳实践

View File

@ -0,0 +1,2 @@
# 用户偏好设置

2
.cunzhi-memory/rules.md Normal file
View File

@ -0,0 +1,2 @@
# 开发规范和规则

59
Dockerfile Normal file
View File

@ -0,0 +1,59 @@
# 使用官方PHP-FPM Alpine镜像作为基础
FROM php:8.4-fpm-alpine
# 设置维护者信息
LABEL maintainer="Common Nginx PHP-FPM Image"
# 安装系统依赖和nginx
RUN apk add --no-cache \
nginx \
supervisor \
postgresql-dev \
mysql-dev \
&& rm -rf /var/cache/apk/*
# 安装常用PHP扩展
RUN docker-php-ext-install \
pdo_mysql \
pdo_pgsql \
pgsql \
mysqli \
opcache
# 创建必要的目录
RUN mkdir -p /var/www/html \
/var/log/nginx \
/var/log/php-fpm \
/etc/supervisor/conf.d \
/var/lib/php/sessions \
/run/nginx && \
chown -R nginx:nginx /var/www/html \
/var/log/nginx \
/var/log/php-fpm \
/var/lib/php/sessions \
/run/nginx
# 复制配置文件
COPY config/nginx.conf /etc/nginx/nginx.conf
COPY config/php.ini /usr/local/etc/php/php.ini
COPY config/www.conf /usr/local/etc/php-fpm.d/www.conf
# 复制supervisor配置
COPY config/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# 复制启动脚本
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
# 设置工作目录
WORKDIR /var/www/html
# 创建默认的index.php文件
RUN echo '<?php phpinfo(); ?>' > /var/www/html/index.php
# 暴露端口
EXPOSE 80
# 设置启动命令
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

166
README.md Normal file
View File

@ -0,0 +1,166 @@
# Common Nginx + PHP-FPM Docker Image
这是一个通用的 Nginx + PHP-FPM Docker 镜像,支持外部配置文件覆盖。
## 🔒 安全版本说明
提供两个版本供选择:
### Alpine版本 (推荐生产环境)
- **镜像标签**: `common-nginx-fpm-alpine`
- **基础镜像**: `php:8.4-fpm-alpine`
- **安全状态**: ✅ 0个高危漏洞
- **镜像大小**: ~754MB
- **推荐用途**: 生产环境、安全要求高的场景
### Debian版本 (开发环境可选)
- **镜像标签**: `common-nginx-fpm`
- **基础镜像**: `php:8.4-fpm`
- **安全状态**: ⚠️ 152个高危漏洞
- **镜像大小**: ~569MB
- **推荐用途**: 开发环境、需要glibc兼容性的场景
> 📋 详细安全对比请查看 [SECURITY_REPORT.md](SECURITY_REPORT.md)
## 特性
- 基于官方 PHP 8.4 FPM 镜像
- 集成 Nginx 作为 Web 服务器
- 支持 PHP 文件动态处理和静态资源服务
- 预装常用 PHP 扩展PDO MySQL, PDO PostgreSQL, PostgreSQL, MySQLi, OPcache
- 支持外部配置文件覆盖
- 使用 Supervisor 管理进程
- 包含健康检查端点
## 快速开始
### 构建镜像
```bash
# 构建Alpine版本 (推荐)
docker build -t common-nginx-fpm-alpine .
# 构建Debian版本 (需要修改Dockerfile第一行)
# 将 FROM php:8.4-fpm-alpine 改为 FROM php:8.4-fpm
docker build -t common-nginx-fpm .
```
### 运行容器
```bash
# Alpine版本 - 基本运行
docker run -d -p 80:80 common-nginx-fpm-alpine
# Alpine版本 - 挂载代码目录
docker run -d -p 80:80 -v /path/to/your/code:/var/www/html common-nginx-fpm-alpine
# Alpine版本 - 安全运行 (推荐生产环境)
docker run -d -p 80:80 \
--name web-app \
--read-only \
--tmpfs /tmp \
--tmpfs /var/run \
--memory=512m \
--cpus=1.0 \
-v /path/to/your/code:/var/www/html:ro \
-v /path/to/custom/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /path/to/custom/php.ini:/usr/local/etc/php/conf.d/custom.ini:ro \
common-nginx-fpm-alpine
# Debian版本 - 基本运行
docker run -d -p 80:80 common-nginx-fpm
```
## 配置覆盖
### Nginx 配置
- 默认配置:`/etc/nginx/nginx.conf`
- 自定义配置:挂载到 `/etc/nginx/nginx.conf``/etc/nginx/conf.d/default.conf`
### PHP 配置
- 默认配置:`/usr/local/etc/php/php.ini`
- 自定义配置:挂载到 `/usr/local/etc/php/conf.d/custom.ini`
### PHP-FPM 配置
- 默认配置:`/usr/local/etc/php-fpm.d/www.conf`
- 自定义配置:挂载到 `/usr/local/etc/php-fpm.d/custom.conf`
## 目录结构
```
/var/www/html/ # Web 根目录
/var/log/nginx/ # Nginx 日志
/var/log/php-fpm/ # PHP-FPM 日志
/var/lib/php/sessions/ # PHP 会话存储
```
## 端口
- `80`: HTTP 端口
## 健康检查
访问 `http://localhost/health` 进行健康检查。
## Docker Compose 示例
```yaml
version: '3.8'
services:
web:
build: .
ports:
- "80:80"
volumes:
- ./src:/var/www/html
- ./config/custom-nginx.conf:/etc/nginx/nginx.conf
- ./config/custom-php.ini:/usr/local/etc/php/conf.d/custom.ini
environment:
- TZ=Asia/Shanghai
```
## 环境变量
- `TZ`: 时区设置默认Asia/Shanghai
## 安全注意事项
- 默认禁用了一些危险的 PHP 函数
- 设置了 open_basedir 限制
- 隐藏了敏感文件和目录
- 添加了安全响应头
## 日志
- Nginx 访问日志:`/var/log/nginx/access.log`
- Nginx 错误日志:`/var/log/nginx/error.log`
- PHP-FPM 错误日志:`/var/log/php-fpm/www-error.log`
- PHP-FPM 慢日志:`/var/log/php-fpm/slow.log`
## 故障排除
### 查看日志
```bash
# 查看容器日志
docker logs <container_id>
# 进入容器查看详细日志
docker exec -it <container_id> bash
tail -f /var/log/nginx/error.log
tail -f /var/log/php-fpm/www-error.log
```
### 测试配置
```bash
# 测试 Nginx 配置
docker exec <container_id> nginx -t
# 测试 PHP-FPM 配置
docker exec <container_id> php-fpm -t
```

146
SECURITY_REPORT.md Normal file
View File

@ -0,0 +1,146 @@
# Docker镜像安全扫描报告
## 概述
本报告对比了两个版本的 nginx + php-fpm Docker 镜像的安全性:
- **Debian版本** (common-nginx-fpm): 基于 `php:8.4-fpm`
- **Alpine版本** (common-nginx-fpm-alpine): 基于 `php:8.4-fpm-alpine`
## 安全扫描结果
### Debian版本 (php:8.4-fpm)
```
扫描时间: 2025-06-25
高危和严重漏洞总数: 152个
- 严重漏洞 (CRITICAL): 3个
- 高危漏洞 (HIGH): 149个
镜像大小: 569MB
```
**主要漏洞类别:**
- 系统库漏洞: glibc, libxml2, zlib
- 内核相关: linux-libc-dev (大量内核CVE)
- 其他组件: libexpat, libicu, openldap
### Alpine版本 (php:8.4-fpm-alpine)
```
扫描时间: 2025-06-25
高危和严重漏洞总数: 0个
- 严重漏洞 (CRITICAL): 0个
- 高危漏洞 (HIGH): 0个
镜像大小: 754MB
```
## 安全对比分析
| 指标 | Debian版本 | Alpine版本 | 改进 |
|------|------------|------------|------|
| 严重漏洞 | 3个 | 0个 | ✅ 100%改进 |
| 高危漏洞 | 149个 | 0个 | ✅ 100%改进 |
| 总漏洞数 | 152个 | 0个 | ✅ 100%改进 |
| 镜像大小 | 569MB | 754MB | ❌ 增加32% |
## 推荐使用方案
### 🏆 生产环境推荐: Alpine版本
**优势:**
- ✅ **零高危漏洞**: 显著提升安全性
- ✅ **更新频率高**: Alpine维护更积极
- ✅ **攻击面小**: 系统组件更少
- ✅ **符合安全最佳实践**
**劣势:**
- ❌ 镜像稍大 (754MB vs 569MB)
- ❌ 可能存在兼容性问题 (musl vs glibc)
### 🔧 开发环境可选: Debian版本
**适用场景:**
- 需要与生产环境完全一致的glibc环境
- 使用依赖glibc特性的第三方库
- 对安全要求不高的内部开发环境
## 安全加固建议
### 1. 运行时安全
```dockerfile
# 非root用户运行
USER nginx
# 只读根文件系统
--read-only --tmpfs /tmp --tmpfs /var/run
# 资源限制
--memory=512m --cpus=1.0
```
### 2. 网络安全
```dockerfile
# 最小权限网络
--network=custom-network
# 端口限制
EXPOSE 80
```
### 3. 定期更新
- 建议每月重新构建镜像
- 监控CVE数据库更新
- 使用自动化安全扫描
## 使用建议
### Alpine版本使用 (推荐)
```bash
# 构建Alpine版本
docker build -t common-nginx-fpm-alpine .
# 安全运行
docker run -d \
--name web-app \
--read-only \
--tmpfs /tmp \
--tmpfs /var/run \
--memory=512m \
--cpus=1.0 \
-p 80:80 \
-v ./app:/var/www/html:ro \
common-nginx-fpm-alpine
```
### 切换到Debian版本 (如需要)
```bash
# 修改Dockerfile第一行
FROM php:8.4-fpm # 替代 php:8.4-fpm-alpine
# 重新构建
docker build -t common-nginx-fpm .
```
## 监控和维护
### 定期安全扫描
```bash
# 使用Trivy扫描
trivy image --severity HIGH,CRITICAL your-image:tag
# 使用Docker Scout (如可用)
docker scout cves your-image:tag
```
### 更新策略
1. **每月更新**: 重新构建基础镜像
2. **紧急更新**: 发现严重漏洞时立即更新
3. **测试验证**: 更新后进行功能测试
## 结论
**强烈推荐使用Alpine版本**用于生产环境,因为:
1. **零高危漏洞**显著提升安全性
2. 安全收益远超镜像大小增加的成本
3. Alpine的维护和更新更加积极
4. 符合现代容器安全最佳实践
对于对安全性要求极高的环境,建议进一步考虑:
- 使用Distroless镜像
- 实施多阶段构建
- 添加运行时安全监控

102
config/nginx.conf Normal file
View File

@ -0,0 +1,102 @@
user nginx;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 访问日志
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# 基本设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100M;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/atom+xml
image/svg+xml;
# 服务器配置
server {
listen 80;
server_name _;
root /var/www/html;
index index.php index.html index.htm;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
# 主要location块
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP文件处理
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# PHP-FPM超时设置
fastcgi_connect_timeout 60s;
fastcgi_send_timeout 60s;
fastcgi_read_timeout 60s;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 隐藏敏感文件
location ~ /\. {
deny all;
}
location ~ ~$ {
deny all;
}
# 健康检查端点
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
}

146
config/php.ini Normal file
View File

@ -0,0 +1,146 @@
[PHP]
; 基本设置
engine = On
short_open_tag = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = -1
disable_functions =
disable_classes =
zend.enable_gc = On
; 错误报告
expose_php = Off
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
html_errors = On
error_log = /var/log/php-fpm/error.log
; 资源限制
max_execution_time = 30
max_input_time = 60
memory_limit = 256M
; 数据处理
post_max_size = 100M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
; 文件上传
file_uploads = On
upload_max_filesize = 100M
max_file_uploads = 20
; Fopen wrappers
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
; 动态扩展
extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20240924"
; 模块设置
[CLI Server]
cli_server.color = On
[Date]
date.timezone = Asia/Shanghai
[filter]
filter.default = unsafe_raw
filter.default_flags =
[iconv]
iconv.input_encoding = UTF-8
iconv.internal_encoding = UTF-8
iconv.output_encoding = UTF-8
[intl]
intl.default_locale =
intl.error_level = E_WARNING
intl.use_exceptions = 0
[sqlite3]
sqlite3.extension_dir =
[Pcre]
pcre.backtrack_limit = 100000
pcre.recursion_limit = 100000
pcre.jit = 1
[Pdo]
pdo_mysql.default_socket =
[Pdo_mysql]
pdo_mysql.default_socket =
[Phar]
phar.readonly = On
phar.require_hash = On
phar.cache_list =
[mail function]
SMTP = localhost
smtp_port = 25
mail.add_x_header = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[OPcache]
opcache.enable = 1
opcache.enable_cli = 1
opcache.memory_consumption = 128
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 2
opcache.fast_shutdown = 1
[curl]
curl.cainfo =
[openssl]
openssl.cafile =
openssl.capath =
[ffi]
ffi.enable = "preload"

23
config/supervisord.conf Normal file
View File

@ -0,0 +1,23 @@
[supervisord]
nodaemon=true
user=root
logfile=/var/log/supervisor/supervisord.log
pidfile=/var/run/supervisord.pid
[program:php-fpm]
command=php-fpm -F
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=true
startretries=0
[program:nginx]
command=nginx -g 'daemon off;'
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=true
startretries=0

54
config/www.conf Normal file
View File

@ -0,0 +1,54 @@
[www]
; 用户和组
user = nginx
group = nginx
; 监听设置
listen = 127.0.0.1:9000
listen.owner = nginx
listen.group = nginx
listen.mode = 0660
listen.allowed_clients = 127.0.0.1
; 进程管理
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
; 进程超时
request_terminate_timeout = 30s
; 日志设置
access.log = /var/log/php-fpm/access.log
access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"
; 慢日志
slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 10s
; 安全设置
security.limit_extensions = .php .phar
; 环境变量
clear_env = no
; PHP配置值
php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 256M
php_admin_value[upload_max_filesize] = 100M
php_admin_value[post_max_size] = 100M
php_admin_value[max_execution_time] = 30
; 会话设置
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/sessions
; 其他设置
php_admin_value[disable_functions] = exec,passthru,shell_exec,system
php_admin_value[open_basedir] = /var/www/html:/tmp:/var/lib/php/sessions

47
docker-entrypoint.sh Normal file
View File

@ -0,0 +1,47 @@
#!/bin/sh
set -e
# 创建必要的目录
mkdir -p /var/log/nginx
mkdir -p /var/log/php-fpm
mkdir -p /var/lib/php/sessions
mkdir -p /var/log/supervisor
# 设置权限
chown -R nginx:nginx /var/www/html
chown -R nginx:nginx /var/lib/php/sessions
chmod 755 /var/lib/php/sessions
# 检查并复制配置文件(支持外部覆盖)
echo "Checking configuration files..."
# 检查nginx配置
if [ -f "/etc/nginx/conf.d/default.conf" ]; then
echo "Using custom nginx configuration from /etc/nginx/conf.d/default.conf"
elif [ ! -f "/etc/nginx/nginx.conf" ]; then
echo "Copying default nginx configuration..."
cp /etc/nginx/nginx.conf.default /etc/nginx/nginx.conf
fi
# 检查PHP配置
if [ -f "/usr/local/etc/php/conf.d/custom.ini" ]; then
echo "Using custom PHP configuration from /usr/local/etc/php/conf.d/custom.ini"
fi
# 检查PHP-FPM配置
if [ -f "/usr/local/etc/php-fpm.d/custom.conf" ]; then
echo "Using custom PHP-FPM configuration from /usr/local/etc/php-fpm.d/custom.conf"
fi
# 测试nginx配置
echo "Testing nginx configuration..."
nginx -t
# 测试PHP-FPM配置
echo "Testing PHP-FPM configuration..."
php-fpm -t
echo "Starting services..."
# 执行传入的命令
exec "$@"