web-ngnix

  1. ngnix 的功能
  2. 静态资源服务
  3. 反向代理 (Reverse Proxy)
  4. 负载均衡(Load Balancing)

ngnix 的功能

静态资源服务

展示一个静态的 webpage

案例:

  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>hello world</p>
    
    <a href="./page2.html">page2</a>
</body>
</html>
  • page2.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p> well come to my page</p>
</body>
</html>
  • docker-compose
services:
  nginx:
    image: nginx
    container_name: my-nginx
    ports:
      - "9002:80"
    volumes:
      - ./html:/usr/share/nginx/html
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./logs:/var/log/nginx

# docker-compose up -d
  • nginx.conf
worker_processes   3;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;
        root         /usr/share/nginx/html;
        index        index.html;

        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

反向代理 (Reverse Proxy)

反向代理示意图

R

image-20250819132810905

案例:

反向代理示例

  • main.py

server 1

from typing import Union
import uvicorn
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

def main():
    uvicorn.run(app, host="127.0.0.1", port=1145)

if __name__ == "__main__":
    main()

所有的 server如下:

127.0.0.1:1145
127.0.0.1:1919

此处的nginx放在docker中,server也跑在docker里的

  • nginx.conf
server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://fastapi_app:1145; 
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

负载均衡(Load Balancing)

github