Containerizing PHP and Nginx with Docker: Step‑by‑Step Guide
This tutorial walks through creating a project structure, writing a simple PHP app, configuring Nginx, authoring Dockerfiles, setting up .dockerignore and docker‑compose.yml, and finally building and running the containers so the PHP service is reachable via Nginx on localhost.
Containerizing a PHP application with Nginx requires creating separate Docker containers for each service and configuring them to work together. The following steps outline a basic Docker setup based on a simple PHP app.
1. Create project structure
Start with a directory layout like:
//projet
├── index.php
├── nginx
│ └── nginx.conf
├── Dockerfile
├── Dockerfile-nginx
└── docker-compose.yml2. Create PHP application
Add a minimal index.php file at the project root:
<?php
echo "Hello!";3. Configure Nginx
Write an Nginx configuration file at nginx/nginx.conf :
server {
listen 80;
index index.php;
server_name localhost;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
error_page 404 /index.php;
root /var/www;
client_max_body_size 20m;
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass app:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}
}4. Write Dockerfile for PHP
FROM php:8.0.2-fpm
WORKDIR /var/www5. Create Dockerfile for Nginx
Place this file in the project root as Dockerfile-nginx :
FROM nginx:1.19-alpine
WORKDIR /var/www6. Create .dockerignore
docker-compose
Dockerfile*7. Write Docker Compose file
version: "3"
services:
app:
container_name: app-container
build:
context: ./
dockerfile: ./Dockerfile
working_dir: /var/www/
restart: always
volumes:
- ./:/var/www
networks:
- app-network
nginx:
container_name: nginx-container
build:
context: ./
dockerfile: ./Dockerfile-nginx
restart: always
ports:
- "8000:80"
volumes:
- ./nginx:/etc/nginx/conf.d
- ./:/var/www
depends_on:
- app
networks:
- app-network
networks:
app-network:
driver: bridgeThe application network connects the PHP and Nginx containers, allowing them to communicate without interfering with the host network.
8. Build and run containers
Execute the following command to build the images and start the services:
docker-compose up --buildThen open http://localhost:8000 in a browser; you should see the message “Hello!”.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.