Drupal docker compose file example with nginx

Note Statistics

Note Statistics

  • Viewed 34 times

This note is based on a previous note where we started with a custom Docker file created inside a Drupal project created with composer.

Sample nginx configuration file

This is a very basic nginx configuration file. Create a file named site.conf

server {
    listen         80 default_server;
    listen         [::]:80 default_server;
    server_name    *.com;
    root           /src/web/;
    index index.php  index.html index.htm;

   try_files $uri $uri/ @rewrite;
   location @rewrite {
        rewrite ^/(.*)$ /index.php?_url=/$1;
   }
  location ~* \.php$ {
    fastcgi_pass php:9000;
    include         fastcgi_params;
    fastcgi_index  index.php;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
  }
}

Sample .env file

# file system
 PRIVATE_FILE_SYSTEM_PATH=/private

# mysql
MYSQL_ROOT_PASSWORD=root
MYSQL_DATABASE=drupal_site
MYSQL_USER=root
MYSQL_PASSWORD=verrysecret
MYSQL_HOSTNAME=host.docker.internal
MYSQL_PORT=3308

Tip In the environment file we are setting MYSQL_HOSTNAME=host.docker.internal. host.docker.internal is telling the container that the MySQL is running on the host machine.

The docker-compose file

Create a docker-compose.yml file with the content below

version: "3"
services:
  php:
    build:
      context: .

    volumes:
      - ./.env:/src/.env
      - ./web/sites/default/settings.php:/src/web/sites/default/settings.php
      - ./web/sites/default/files:/src/web/sites/default/files
      - web-volume:/src/web

  nginx:
    image: nginx:latest

    volumes:
      - web-volume:/src/web
      - ./site.conf:/etc/nginx/conf.d/site.conf
    depends_on:
      - php

volumes:
  web-volume:

In the docker-compose file above two services are defined.

  • php: Is your Drupal site running behind php-fpm
  • nginx: The nginx reverse proxy that would forward requests to your Drupal site.

Environment specific docker-compose files

Ideally you want to be able to run your Drupal project in development (or local) environment and production. Since is it likely that production and development environment are not identical we can use additional docker-ccompose files that can overrride the default configuration. For example you can define a development file.

Create a file named docker-compose.development.yml with the content below

version: "3"
services:
    nginx:
    ports:
      - 80:80

We are adding an additional configuration to the nginx service defined in the original docker-compose file configuration. We are telling docker to expose the nginx container on port 80 of the host.

You can then run your Drupal site from the root directory of your project with

docker-compose -f docker-compose.yml -f docker-compose.development.yml up
Authored by
HappyDev