Skip to content

🚀 实战案例:部署完整 Web 应用

场景:Nginx + Node.js + MySQL 全栈应用

让我们来部署一个真实项目:Nginx 做反向代理,Node.js 做后端 API,MySQL 做数据库。

项目结构:

text
my-project/
├── docker-compose.yml
├── nginx/
│   └── nginx.conf
├── backend/
│   ├── Dockerfile
│   ├── package.json
│   └── app.js
└── frontend/
    └── dist/
        ├── index.html
        └── ...

docker-compose.yml:

yaml
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      - ./frontend/dist:/usr/share/nginx/html
    depends_on:
      - backend
    restart: unless-stopped

  backend:
    build: ./backend
    environment:
      - DB_HOST=db
      - DB_PORT=3306
      - DB_USER=root
      - DB_PASS=secretpassword
      - DB_NAME=webapp
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: secretpassword
      MYSQL_DATABASE: webapp
    volumes:
      - mysql-data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 10s
      timeout: 5s
      retries: 5
    restart: unless-stopped

volumes:
  mysql-data:

nginx.conf:

nginx
server {
    listen 80;
    server_name example.com;

    # 静态文件
    location / {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    # API 反向代理
    location /api/ {
        proxy_pass http://backend:3000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

一键启动:

bash
# 构建并启动所有服务
docker compose up -d --build
[+] Building 25.3s (12/12) FINISHED
[+] Running 4/4
 Network my-project_default      Created
 Container my-project-db-1       Healthy
 Container my-project-backend-1  Started
 Container my-project-nginx-1    Started

# 验证所有服务
docker compose ps
curl http://localhost
curl http://localhost/api/users