Docker Compose 一键部署 LNMP 环境(含完整配置文件)

一、目录结构

CODE
lnmp/
├── docker-compose.yml
├── nginx/
│   ├── nginx.conf
│   └── conf.d/
│       └── default.conf
├── php/
│   └── Dockerfile
├── mysql/
│   └── my.cnf
└── www/
    └── index.php

二、docker-compose.yml

YAML
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 配置

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

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

五、启动与验证

Bash
docker compose up -d
docker compose ps
docker compose logs -f nginx

访问 http://localhost 看到 PHP 信息页即成功。

六、常见坑

  1. 502 Bad Gateway:检查 fastcgi_pass 是否用了服务名 php:9000 而非 127.0.0.1
  2. 文件权限:宿主机 www 目录需 755,PHP 容器用户是 www-data
  3. MySQL 连不上:容器间用服务名 mysql 互联,不要用 localhost
  4. 时区不对:每个服务都加 TZ: Asia/Shanghai
打赏作者 已有 0 人打赏,共 ¥0.00
我的打赏
运维老王
运维老王
Lv7 普通VIP 原创 3 粉丝 2730

K8s / Docker / CICD 一线运维,踩坑专业户

  • 3文章
  • 13.2万总阅读
  • 4649获赞
  • 2730粉丝

评论(2)

安全小白帽・澳大利亚
爬虫记得遵守 robots.txt,别给对方服务器造成压力。
28天前 👍 54 回复 举报
Python猫哥・澳大利亚
说得对,框架里已经内置了 delay 限速,生产环境建议再加代理池。
1个月前 👍 53 回复 举报