Before you go, check out these stories!

0
Hackernoon logoNginx + PHP + Docker: How To Get PHP Page Up With Local Domain Name by@ifomin

Nginx + PHP + Docker: How To Get PHP Page Up With Local Domain Name

Author profile picture

@ifominIgor Fomin

Full stack web developer, tech lead, project manager

I will setup a very simple php page with docker and nginx.

Source files can be found here:

https://github.com/ikknd/docker-study in folder recipe-02

1. Create a project folder setup:

/var/www/docker-study.loc/recipe-02
	-> /docker
	-> /php

In "php" folder I will create index.php file that executes phpinfo().

2. Create nginx config site.conf in "docker" folder:

server {
    server_name myapp.loc;

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

    access_log /var/log/nginx/back-access.log;
    error_log /var/log/nginx/back-error.log;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP-FPM Configuration Nginx
    location ~ \.php$ {
        try_files $uri = 404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param REQUEST_URI $request_uri;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

fastcgi_pass php:9000;
- this is what tells nginx how to connect to php container

3. Edit /etc/hosts file on host machine, and add a record:

127.0.0.1       myapp.loc

4. Create docker-compose.yml file in "docker" folder:

version: "3.7"

services:

  web:
    image: nginx:1.17
    ports:
      - 80:80
    volumes:
      - /var/www/docker-study.loc/recipe-02/php:/var/www/myapp
      - /var/www/docker-study.loc/recipe-02/docker/site.conf:/etc/nginx/conf.d/site.conf
    depends_on:
      - php

  php:
    image: php:7.2-fpm
    volumes:
      - /var/www/docker-study.loc/recipe-02/php:/var/www/myapp
      - /var/www/docker-study.loc/recipe-02/docker/php.ini:/usr/local/etc/php/php.ini

Here I do several things:

  • I use my own php.ini file, that I copy to php container, so if I need to change some settings, I simply do changes in php.ini and restart container
  • If I do changes in php code in index.php file, there is no need to restart container, changes get applied immediately with browser page reload.
  • "depends_on" - prevents container to start before other container, on which it depends

5. Go to /var/www/docker-study.loc/recipe-02/docker/ and execute:

docker-compose up -d

If I now try

myapp.loc/
in browser, I will see php info results.

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!