You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker环境Nginx访问PHP返回403 Forbidden错误排查求助

docker-compose搭建Nginx+PHP+MySQL环境403报错及PHP无法解析解决方法

核心问题原因

该问题由3处配置不匹配导致:

  • Nginx容器内挂载路径与站点配置的root路径不一致
  • Nginx转发PHP请求的地址错误,无法跨容器通信到PHP服务
  • PHP容器的挂载路径与本地目录结构不匹配,找不到PHP文件

具体解决步骤

1. 修正docker-compose.yml配置

统一Nginx和PHP的代码挂载路径,修改对应配置段:

version: "3"
networks:
  laravel:

services:
  nginx:
    image: nginx:stable-alpine
    container_name: nginx
    ports:
      - "8088:80"
    volumes: 
      # 统一挂载到/var/www/html,和PHP服务路径保持一致
      - ./src:/var/www/html
      - ./site.conf:/etc/nginx/conf.d/site.conf
    depends_on:
      - php
      - mysql
    networks:
    - laravel

  mysql:
    image: mysql:5.7.35
    container_name: mysql
    restart: unless-stopped
    tty: true
    ports: 
      - "4306:3306"
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      MYSQL_DATABASE: boilerplatelaravel
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: Tobi12345678
    networks:
      - laravel

  php:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: php
    volumes:
      # 修正挂载路径,匹配本地src目录结构
      - ./src:/var/www/html
    ports:
      - "9000:9000"
    networks:
      - laravel

2. 修正site.conf Nginx配置

修改root路径与fastcgi转发地址:

server {
    listen 80;
    # 补充index.html兼容静态文件访问
    index index.php index.html;
    server_name localhost;
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    # 匹配挂载后的代码路径,如需laravel结构则改为/var/www/html/public,同时本地src下新建public目录放index.php
    root /var/www/html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # 用PHP服务名通信,同docker网络下不能用127.0.0.1
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

3. 修正目录权限

执行本地命令确保代码目录允许容器内用户读取:

chmod -R 755 ./src

4. 重启容器生效配置

docker-compose down && docker-compose up -d --build

修改完成后访问localhost:8088/index.php即可正常看到phpinfo输出。

内容的提问来源于stack exchange,提问作者Tobiaske1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:39:03