Introduction
In this article, we will discuss how to set up a PHP web server using Docker Compose and Nginx Proxy. We will create two domains, one for static files served by Nginx, and another for dynamic content handled by the PHP server.
Prerequisites
Before we begin, make sure you have the following tools installed:
- Docker
- Docker Compose
Setting Up the Docker Compose File
Create a new file named "docker-compose.yml" in a new directory:
version: '3.8'
services:
nginx:
image: nginx:latest
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d
- ./nginx/html:/usr/share/nginx/html
- ./certs:/etc/nginx/certs
php:
image: php:7.4-fpm
volumes:
- ./php:/var/www/html
Creating the Nginx Configuration
Create a new directory named "nginx" and create two new files inside it:
- conf.d/default.conf
- html/index.html
Nginx Configuration
Edit the "default.conf" file:
server { listen 80; listen [::]:80; server_name static.example.com; root /usr/share/nginx/html; location / { try_files $uri $uri/ /index.html; } location ~ \.php$ { proxy_pass http://php:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; index index.php; }
location ~ /.ht { deny all; } }
Creating Static Files
Create a new file named "index.html" in the "html" directory:
Static Files
Welcome to Static Files
Running the Application
Build and run the Docker Compose application:
docker-compose up -d
Testing the Application
Open your web browser and visit:
- http://static.example.com
Setting Up the PHP Server
Create a new file named "index.php" in the "php" directory:
Nginx Proxy for PHP
Edit the "default.conf" file again:
server { listen 80; listen [::]:80; server_name dynamic.example.com; root /usr/share/nginx/html; location / { try_files $uri $uri/ /index.html; } location ~ \.php$ { proxy_pass http://php:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; index index.php; }location ~ /.ht { deny all; }
upstream php { server php:9000; } }
Testing the PHP Server
Open your web browser and visit:
- http://dynamic.example.com
Conclusion
In this article, we learned how to set up a PHP web server using Docker Compose and Nginx Proxy. We created two domains, one for static files served by Nginx, and another for dynamic content handled by the PHP server.