一、目录结构
lnmp/
├── docker-compose.yml
├── nginx/
│ ├── nginx.conf
│ └── conf.d/
│ └── default.conf
├── php/
│ └── Dockerfile
├── mysql/
│ └── my.cnf
└── www/
└── index.php
二、docker-compose.yml
version: '3.8'
services:
nginx:
image: nginx:1.25-alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./www:/var/www/html
- ./nginx/conf.d:/etc/nginx/conf.d
- ./nginx/logs:/var/log/nginx
depends_on:
- php
networks:
- lnmp
php:
build: ./php
volumes:
- ./www:/var/www/html
depends_on:
- mysql
- redis
networks:
- lnmp
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root123456
MYSQL_DATABASE: app_db
TZ: Asia/Shanghai
volumes:
- mysql_data:/var/lib/mysql
- ./mysql/my.cnf:/etc/mysql/conf.d/my.cnf
ports:
- "3306:3306"
networks:
- lnmp
redis:
image: redis:7-alpine
command: redis-server --requirepass redis123
ports:
- "6379:6379"
networks:
- lnmp
volumes:
mysql_data:
networks:
lnmp:
driver: bridge
三、Nginx 配置
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
四、PHP Dockerfile
FROM php:8.2-fpm-alpine
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
&& apk add --no-cache libpng-dev libzip-dev freetype-dev libjpeg-turbo-dev
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd pdo_mysql mysqli zip opcache
RUN pecl install redis && docker-php-ext-enable redis
五、启动与验证
docker compose up -d
docker compose ps
docker compose logs -f nginx
访问 http://localhost 看到 PHP 信息页即成功。
六、常见坑
- 502 Bad Gateway:检查
fastcgi_pass是否用了服务名php:9000而非127.0.0.1 - 文件权限:宿主机
www目录需 755,PHP 容器用户是www-data - MySQL 连不上:容器间用服务名
mysql互联,不要用 localhost - 时区不对:每个服务都加
TZ: Asia/Shanghai
评论(2)