How To Link PHP-FPM And Nginx Docker Containers?

Published August 29, 2024

Problem: Connecting PHP-FPM and Nginx Docker Containers

Linking PHP-FPM and Nginx Docker containers can be difficult. This setup is needed for running PHP applications in a containerized environment, but it requires correct configuration for good communication between the two services.

Configuring Nginx and PHP-FPM Containers

Docker Compose Configuration

To connect Nginx and PHP-FPM containers, update your docker-compose.yml file:

nginx:
  build: .
  ports:
    - "80:80"
  volumes:
    - ./:/complex/path/to/files/
  links:
    - fpm

fpm:
  image: php:fpm
  ports:
    - ":9000"
  volumes:
    - ./:/complex/path/to/files/

This configuration links the Nginx and PHP-FPM containers and sets up volume mounts for shared files.

Tip: Environment Variables for Flexibility

Use environment variables in your docker-compose.yml file to make your configuration more flexible and easier to manage across different environments:

nginx:
  build: .
  ports:
    - "${NGINX_PORT:-80}:80"
  volumes:
    - ${APP_PATH:-./}:/complex/path/to/files/
  links:
    - fpm

fpm:
  image: php:fpm
  ports:
    - "${PHP_FPM_PORT:-9000}"
  volumes:
    - ${APP_PATH:-./}:/complex/path/to/files/

This allows you to easily change ports and file paths by setting environment variables or using a .env file.

Nginx Configuration

Update your Nginx virtual host configuration (default.conf) as follows:

server {
    listen 80;
    root /complex/path/to/files;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/.+\.php(/|$) {
        fastcgi_pass fpm:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

This configuration updates the fastcgi_pass directive to use the container name 'fpm' and port 9000. It also sets the correct root path for handling PHP scripts.

PHP-FPM Container Setup

The PHP-FPM container listens on port 9000 by default. Make sure the file paths in the PHP-FPM container match those in the Nginx container. Both containers should have access to the files at '/complex/path/to/files/'.

By aligning the file paths and configurations between Nginx and PHP-FPM containers, you allow proper communication and execution of PHP scripts.