How to correctly link php-fpm and Nginx Docker containers?

后端 未结 7 965
天涯浪人
天涯浪人 2020-12-02 04:20

I am trying to link 2 separate containers:

  • nginx:latest
  • php:fpm

The problem is that php scripts do not work. Perhaps the php-fpm config

相关标签:
7条回答
  • 2020-12-02 04:52

    As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.

    Updated my example files below with this latest revelation (thank you @alkaline )

    This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)

    docker-compose.yml:

    version: '2'
    services:
      php:
        container_name: test-php
        image: php:fpm
        volumes:
          - ./code:/var/www/html/site
      nginx:
        container_name: test-nginx
        image: nginx:latest
        volumes:
          - ./code:/var/www/html/site
          - ./site.conf:/etc/nginx/conf.d/site.conf:ro
        ports:
          - 80:80
    

    (UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)

    In the same folder:

    site.conf:

    server
    {
        listen   80;
        server_name site.local.[YOUR URL].com;
    
        root /var/www/html/site;
        index index.php;
    
        location /
        {
            try_files $uri =404;
        }
    
        location ~ \.php$ {
            fastcgi_pass   test-php:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
    

    In folder code:

    ./code/index.php:

    <?php
    phpinfo();
    

    and don't forget to update your hosts file:

    127.0.0.1 site.local.[YOUR URL].com
    

    and run your docker-compose up

    $docker-compose up -d
    

    and try the URL from your favorite browser

    site.local.[YOUR URL].com/index.php
    
    0 讨论(0)
提交回复
热议问题