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

后端 未结 7 990
天涯浪人
天涯浪人 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:40

    As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

    Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

    Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

    version: "2"
    services:
      nginx:
        build:
          context: .
          dockerfile: nginx/Dockerfile
        ports:
          - "80:80"
        links:
          - fpm
        volumes_from:
          - data
      fpm:
        image: php:fpm
        volumes_from:
          - data
      data:
        build:
          context: .
          dockerfile: data/Dockerfile
        volumes:
          - /var/www/html
    

    Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

    FROM busybox
    
    # content
    ADD path/to/source /var/www/html
    

    And the Dockerfile for nginx, that just replaces the default config:

    FROM nginx
    
    # config
    ADD config/default.conf /etc/nginx/conf.d
    

    For the sake of completion, here's the config file required for the example to work:

    server {
        listen 0.0.0.0:80;
    
        root /var/www/html;
    
        location / {
            index index.php index.html;
        }
    
        location ~ \.php$ {
            include fastcgi_params;
            fastcgi_pass fpm:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        }
    }
    

    which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

提交回复
热议问题