需确保php扩展(pdo、mbstring等)完整启用、使用statefulset绑定pvc持久化配置与日志、配置memory指标驱动的hpa防oom、ingress正确重写url,并通过livenessprobe:/healthz保障服务健康。

在Kubernetes集群中稳定运行Yii3.0应用,需确保PHP运行时、容器镜像构建、资源配置与服务暴露全部适配云原生规范,避免因扩展加载缺失或资源限制过严导致Pod反复CrashLoopBackOff。
构建兼容K8s的Yii3.0容器镜像
使用Alpine基础镜像可显著减小体积,但必须手动启用PDO、OpenSSL、mbstring等Yii3运行必需扩展。
创建Dockerfile:
FROM php:8.3-alpine
RUN apk add --no-cache nginx supervisor curl git && \ docker-php-ext-install pdo_mysql mbstring opcache && \ pecl install xdebug && docker-php-ext-enable xdebug
COPY ./app /var/www/html
RUN chown -R www-data:www-data /var/www/html && \ chmod +x /var/www/html/yii
EXPOSE 80
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
这一步不能跳过:Yii3默认依赖ext-pdo和ext-mbstring,Alpine镜像默认不启用,【缺少任一扩展将导致应用启动失败且无明确报错】。
编写StatefulSet部署Yii3应用
Yii3应用通常需要持久化配置(如.env)、日志路径及上传目录,用StatefulSet比Deployment更利于绑定PVC。
第一步:创建ConfigMap挂载环境变量
kubectl create configmap yii3-config --from-file=.env=./.env.prod --namespace=prod
第二步:声明PersistentVolumeClaim用于日志与上传存储
apiVersion: v1kind: PersistentVolumeClaimmetadata: name: yii3-storage namespace: prodspec: accessModes: [ReadWriteOnce] resources: requests: storage: 2Gi
第三步:定义StatefulSet,注意volumeMounts路径与Yii3实际写入路径严格一致
volumeMounts:- name: config mountPath: /var/www/html/.env subPath: .env- name: storage mountPath: /var/www/html/runtime- name: storage mountPath: /var/www/html/web/uploads
第四步:设置livenessProbe与readinessProbe路径为/healthz,需在Yii3中提前注册该路由并返回200。
配置Ingress暴露Yii3服务
方法一:使用标准nginx-ingress控制器
创建Ingress资源,host字段必须与集群DNS解析策略匹配,否则404
apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: yii3-ingress namespace: prod annotations: nginx.ingress.kubernetes.io/rewrite-target: /$2 nginx.ingress.kubernetes.io/use-regex: "true"spec: ingressClassName: nginx rules: - host: app.example.com http: paths: - path: /(/|$)(.*) pathType: ImplementationSpecific backend: service: name: yii3-service port: number: 80
方法二:若使用Traefik,需额外添加traefik.ingress.kubernetes.io/router.middlewares注解启用重写中间件,否则Yii3的URL Manager规则无法生效。
配置HorizontalPodAutoscaler自动扩缩容
Yii3应用CPU使用率波动大,尤其在处理文件上传或报表导出时,应基于memory指标而非CPU触发扩容。
第一步:确认metrics-server已就绪
kubectl get apiservice | grep metrics
第二步:创建HPA,最小副本设为2,避免单点故障
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: yii3-hpa namespace: prodspec: scaleTargetRef: apiVersion: apps/v1 kind: StatefulSet name: yii3-app minReplicas: 2 maxReplicas: 6 metrics: - type: Resource resource: name: memory target: type: Utilization averageUtilization: 75
这一步很重要:Yii3的内存占用具有突发性,【仅监控CPU会导致扩缩容滞后,Pod OOM被Kill】。
验证Yii3 Pod健康状态
进入Pod执行诊断命令:
kubectl exec -it yii3-app-0 -n prod -- sh
检查PHP扩展是否完整加载:
php -m | grep -E "(pdo|mbstring|opcache)"
验证Yii3应用入口是否可响应:
curl -I http://localhost/index.php?r=site%2Fhealth
确认容器内Nginx进程运行正常:
ps aux | grep nginx
若返回HTTP 502,说明Supervisor未正确拉起Nginx子进程,需检查/etc/supervisor/conf.d/supervisord.conf中autostart=true和startsecs=10是否设置。











