Search code examples
phpdockernginxdocker-compose

Why specify the same volume for two services?


This is more of a why? question. I have the below docker-compose.yml file.


services:
  nginx:
    image: nginx:1.25
    container_name: nginx
    ports:
      - "80:80"
    volumes:
      - ./.docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
      - ./app:/var/www/html
    depends_on:
      - php
    networks:
      - app-network

  php:
    image: php:8.3-fpm
    container_name: php
    volumes:
      - ./app:/var/www/html
    networks:
      - app-network

  mariadb:
    image: mariadb:11.3
    container_name: mariadb
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_DATABASE: mydatabase
      MYSQL_USER: myuser
      MYSQL_PASSWORD: mypassword
    ports:
      - "3306:3306"
    volumes:
      - dbdata:/var/lib/mysql
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  dbdata: {}

Separately I have the following nginx file (default.conf in the above).

server {
    listen 80;
    server_name localhost;

    root /var/www/html;
    index index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

My question is for the volumes: for php and nginx on docker-compose.yml. I wanted to know why I would specify the same volume for two containers and not just nginx? I was under the impression that any file that is loaded by nginx is passed through the php container via the fastcgi_pass address location. Therefore only nginx needs to have the volume mounted.


Solution

  • Suppose that your project looks like this:

    ├── app
    │   ├── index.php
    │   └── static.html
    ├── default.conf
    └── docker-compose.yml
    

    In app/ there is both a PHP source file and a static HTML file.

    This is a simplified docker-compose.yml:

    services:
      nginx:
        image: nginx:1.25
        container_name: nginx
        ports:
          - "80:80"
        volumes:
          - ./default.conf:/etc/nginx/conf.d/default.conf
          - ./app:/var/www/html
        depends_on:
          - php
    
      php:
        image: php:8.3-fpm
        container_name: php
        volumes:
          - ./app:/var/www/html
    

    The app/ directory needs to be volume mounted on both services.

    The php service is there to transform the .php files into HTML. So the .php files need to be available to this service. If there is no volume mount here then PHP-FPM has nothing to process.

    PHP-FPM does not process static files, so static files need to be volume mounted on the nginx service directly as well. You can remove the PHP-FPM service and the static file will still work fine.