Skip to content

Nginx 前端开发环境反向代理例子

在前端开发过程中,使用 Nginx 作为反向代理可以有效解决跨域请求问题,同时还可以模拟生产环境的行为。以下是在 Windows、Mac 以及 Windows/Mac 下的 Docker Desktop 环境中配置 Nginx 反向代理的指南。

Windows 和 Mac 上的 Nginx 反向代理

安装 Nginx

  • Windows:访问 Nginx 官网 下载 Windows 版本的 Nginx,解压缩到你的工作目录。
  • Mac:使用 Homebrew 安装 Nginx,打开终端,运行命令 brew install nginx

配置反向代理

  1. 打开 Nginx 配置文件:对于 Windows,通常位于解压缩的 Nginx 目录下的 conf/nginx.conf。对于 Mac,通常位于 /usr/local/etc/nginx/nginx.conf

  2. 编辑配置文件:找到 server 块,修改或添加如下配置,假设你的前端项目运行在 localhost:5173,而 API 服务运行在 https://docs.ffffee.com:8443

Details
nginx
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

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

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen  80;
        server_name  localhost;

        location / {
            proxy_pass http://localhost:5173; # 前端项目
        }

        location /api/ {
            proxy_pass https://docs.ffffee.com:8443; # 后端的 API 服务
            # 或者使用 host.docker.internal 如果 API 在宿主机上
            # proxy_pass http://host.docker.internal:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
  1. 启动/重启 Nginx

    • Windows:运行 start nginx.\nginx -s stop.\nginx -s reload 或重新启动 Nginx 以应用配置更改。
    • Mac:运行 sudo nginxsudo nginx -s reload 以重新加载配置。

Docker Desktop 环境下的 Nginx 反向代理

在使用 Docker Desktop 时,配置 Nginx 反向代理主要考虑网络隔离和服务发现。

1. 创建 Nginx 配置文件

在项目目录中创建 nginx.conf,配置如下,其中 api-service 是你的 API 容器的名称或者使用 host.docker.internal 指向宿主机:

Details
nginx
# 定义事件模块配置,这里设置了 worker 进程能够同时打开的最大连接数为 1024。
events {
    worker_connections  1024;
}

# http 模块用于定义 HTTP 服务的配置。
http {
    # server 块定义了一个虚拟服务器,用于处理客户端的请求。
    server {
        listen  80; # 监听 80 端口,这是 HTTP 默认的端口号。

        # location / 用于匹配所有请求的根路径。
        # 所有指向根路径的请求都会被转发到指定的代理地址。
        location / {
            proxy_pass http://host.docker.internal:5173; # 代理传递请求到宿主机的 5173 端口,通常用于前端项目。
        }

        # location /api/ 用于匹配所有以 /api/ 开头的请求路径。
        location /api/ {
            # proxy_pass http://api-service:3000; # 将请求代理到 Docker 容器中名为 api-service 的服务,监听在 3000 端口。
            proxy_pass https://docs.ffffee.com:8443; # 或者,代理请求到外部的后端 API 服务,此处以 https://docs.ffffee.com:8443 为例。

            # 设置代理请求的头部信息,以确保后端服务能够接收到正确的客户端信息。
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

2. 创建 Dockerfile 文件

文件内容如下

Dockerfile
# 使用官方 Nginx 镜像作为基础镜像。
FROM nginx:latest

# 将本地的 Nginx 配置文件复制到容器内的指定位置,替换掉默认配置。
# 这一步是将我们定制化的 nginx.conf 文件放到容器中 Nginx 默认读取配置文件的位置。
COPY nginx.conf /etc/nginx/nginx.conf

3. 构建镜像

bash
docker build -t my-nginx .
  • docker build: Docker 命令用来构建镜像。
  • -t my-nginx: -t 选项用于为新建的镜像指定一个标签,这里标签为 my-nginx。这样,你就可以通过标签来引用镜像,而不仅仅是 ID。
  • .: 指定 Dockerfile 文件的位置。这里的 . 表示当前目录,Docker 会在当前目录查找名为 Dockerfile 的文件。

4. 运行容器

bash
docker run --name my-nginx-proxy -p 80:80 -d my-nginx
  • docker run: Docker 命令用来运行一个新容器。
  • --name my-nginx-proxy: 为运行的容器指定一个名称 my-nginx-proxy。这允许你通过名字来引用容器,而不只是通过容器的 ID。
  • -p 80:80: 端口映射选项。将容器内的 80 端口映射到宿主机的 80 端口。格式为 <宿主机端口>:<容器端口>
  • -d: 以守护(后台)模式运行容器。
  • my-nginx: 使用的镜像名称,这里是之前构建的 my-nginx 镜像。

5. 常用 Docker 容器操作命令

Details
  • 查看正在运行的容器
bash
docker ps
  • 查看所有容器(包括未运行的)
bash
docker ps -a
  • 停止运行中的容器
bash
docker stop my-nginx-proxy

使用 docker stop 后跟容器名或 ID 来停止一个运行中的容器。

  • 启动已停止的容器
bash
docker start my-nginx-proxy

使用 docker start 后跟容器名或 ID 来启动一个已停止的容器。

  • 重启容器
bash
docker restart my-nginx-proxy

使用 docker restart 后跟容器名或 ID 来重启一个容器。

  • 查看容器的日志
bash
docker logs my-nginx-proxy

使用 docker logs 后跟容器名或 ID 来查看容器的输出日志。

  • 删除容器
bash
docker rm my-nginx-proxy

使用 docker rm 后跟容器名或 ID 来删除已停止的容器。如果要删除运行中的容器,需要先停止容器,或使用 -f(force)选项强制删除。

  • 进入容器
bash
docker exec -it my-nginx-proxy /bin/bash

使用 docker exec 后跟 -it(交互式 tty)和容器名或 ID,以及要执行的命令(如 /bin/bash)来进入运行中的容器内部。这对于调试或配置容器内部环境非常有用。

6. docker compose 的方式

如果你想通过 docker-compose.yml 文件来启动 Nginx 反向代理服务,你可以创建一个包含 Nginx 服务定义的 docker-compose.yml 文件。这种方式可以简化服务的部署和管理,特别是当你需要同时运行多个服务时。

yaml
version: "3" # 指定使用的 Docker Compose 文件版本。版本3是较新的版本之一,提供了大量功能。

services: # 定义了要运行的服务容器。这里我们定义了一个服务。
  nginx: # 服务的名称,这里使用 nginx 作为服务名称。
    image: my-nginx # 指定服务容器使用的镜像,这里使用之前构建的 my-nginx 镜像。
    ports: # 端口映射配置,将容器的端口映射到宿主机的端口。
      - "80:80" # 将容器的 80 端口映射到宿主机的 80 端口,允许通过宿主机的 80 端口访问 Nginx 服务。
    volumes: # 卷映射配置,将宿主机的文件或目录挂载到容器内的指定路径。
      - ./nginx.conf:/etc/nginx/nginx.conf:ro # 将宿主机当前目录下的 nginx.conf 文件挂载到容器内的 /etc/nginx/nginx.conf,只读模式。
  • 停止并删除容器、网络、卷和镜像
bash
docker compose down

这个命令会停止并删除通过 docker-compose.yml 文件定义的所有服务的容器,以及默认网络。如果配合 -v 参数使用,则也会删除所有挂载的卷。

  • 构建并启动服务
bash
docker compose up --build -d
  • --build 参数表示在启动服务之前先构建(或重新构建)镜像。
  • -d 参数(即 --detach)表示在后台运行服务,不会在当前终端显示日志输出。

7. 其他 Docker Compose 常用命令

Details
  • 查看服务日志
bash
docker compose logs

这个命令用于查看服务的输出日志。如果只想查看某个特定服务的日志,可以在命令后添加服务名。

  • 列出运行的容器
bash
docker compose ps

该命令用于列出当前目录下 docker-compose.yml 文件定义的所有服务的容器状态。

  • 重新启动服务
bash
docker compose restart

该命令用于重新启动一个或多个服务。

  • 停止服务
bash
docker compose stop

该命令用于停止运行中的服务,不会删除容器。

  • 启动服务
bash
docker compose start

用于启动已经存在但被停止的服务容器。

访问应用

无论是直接在 Windows/Mac 上配置,还是在 Docker Desktop 环境下,你现在可以通过 http://localhost 访问你的前端应用,并且 /api/ 路径的请求将被代理到指定的 API 服务。

以上是在不同环境下配置 Nginx 反向代理的基本步骤,帮助前端开发环境解决跨域问题,以及模拟更复杂的生产环境配置。