yaml:
-------------------------------
# docker-compose.yml
version: '3'
services:
nginx:
image: nginx:alpine
container_name: nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./src:/var/www/html
- ./nginx.conf:/etc/nginx/nginx.conf
- ./logs/nginx:/var/log/nginx
depends_on:
- php-fpm
php-fpm:
image: php:8.2-fpm-alpine
container_name: php-fpm
volumes:
- ./src:/var/www/html
- ./php/php.ini:/usr/local/etc/php/php.ini
- ./logs/php:/var/log/php
expose:
- "9000"
networks:
default:
driver: bridge
--------------------------------
文件结构:
. ├── src/ # 你的网站源码 ├── nginx.conf # Nginx 配置文件 ├── logs/ │ ├── nginx/ │ └── php/ └── php/ └── php.ini # PHP 配置文件
Nginx 示例配置 (nginx.conf
):
-------------------------------
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 主 server 配置
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php index.html;
location / {
if (-f $request_uri/index.php) {
rewrite (.*?) $request_uri/index.php last;
}
try_files $request_uri/index.html $request_uri/index.htm @index;
}
location @index {
if (!-f $request_filename) {
rewrite (.*?) /index.php last;
}
}
location ~ [^/]\.php(/|$) {
try_files $uri /index.php;
fastcgi_pass php-fpm:9000;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
# 其他全局 HTTP 配置
sendfile on;
keepalive_timeout 65;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
}
-------------------------------
命令:
-------------------------------
# 构建镜像(如果使用自定义Dockerfile)
docker-compose build --no-cache
# 启动服务
docker-compose up -d
# 查看日志
docker-compose logs -f nginx
-------------------------------
命令 | 说明 | 示例 |
---|---|---|
启动服务 | 创建并启动所有容器(默认使用 docker-compose.yml ) | docker-compose up |
后台启动 | 以守护进程模式启动容器 | docker-compose up -d |
停止服务 | 停止所有正在运行的容器 | docker-compose down |
重建服务 | 重新构建镜像并启动容器(适合修改 Dockerfile 后) | docker-compose up --build |
命令 | 说明 | 示例 |
---|---|---|
启动单个服务 | 仅启动指定服务(如 nginx ) | docker-compose up nginx |
停止单个服务 | 停止指定服务 | docker-compose stop nginx |
重启服务 | 重启指定服务 | docker-compose restart nginx |
查看容器状态 | 显示所有容器的运行状态 | docker-compose ps |
查看服务日志 | 实时查看服务日志(-f 持续跟踪) | docker-compose logs -f nginx |
命令 | 说明 | 示例 |
---|---|---|
进入容器终端 | 进入正在运行的容器内部 | docker-compose exec nginx sh |
执行单次命令 | 在容器内执行一次性命令 | docker-compose exec nginx nginx -t |
强制重建服务 | 忽略缓存并重新构建镜像 | docker-compose build --no-cache |
查看镜像信息 | 列出项目使用的镜像 | docker-compose images |
命令 | 说明 | 示例 |
---|---|---|
删除容器 & 网络 | 移除所有容器和网络(保留数据卷) | docker-compose down |
删除容器 & 数据卷 | 彻底清理容器、网络和数据卷 | docker-compose down -v |
删除所有镜像 | 移除项目相关的镜像 | docker-compose down --rmi all |
命令 | 说明 | 示例 |
---|---|---|
指定配置文件 | 使用自定义的 compose 文件 | docker-compose -f docker-compose-prod.yml up |
扩展服务实例 | 启动多个实例(如 3 个 web 服务) | docker-compose up --scale web=3 |
环境变量文件 | 使用 .env 文件注入配置 | 创建 .env 并定义变量(如 MYSQL_ROOT_PASSWORD=123 ) |
最新评论: