如何使用nginx将请求分发到容器

lndjwyie  于 2023-04-05  发布在  Nginx
关注(0)|答案(1)|浏览(126)

嘿,我现在有点笨,配置一个nginx。
我的目标是为我的REST端点获取以下配置:

  • http://localhost/app-one/ping-〉http://app-one:1111/ping
  • http://localhost/app-two/ping-〉http://app-two:2222/ping

这意味着如果我从浏览器调用http://localhost/app-one/ping,它应该被转发到我的docker环境中的http://app-one:1111/ping
下面是我docker和docker composer文件的一个非常简化的表示:

FROM nginx:alpine
COPY ./nginx.conf /etc/nginx/nginx.conf
version: '3.7'
services:
  proxy:
    image: "proxy"
    build: ./nginx-data
    ports:
    - "80:80"
    environment:
    - NGINX_PORT=80
  app-one:
    image: "app-one"
    container_name: app-one
  app-two:
    image: "app-two"
    container_name: app-two

下面是我失败的nginx配置尝试:

worker_processes 1;
  
events { worker_connections 1024; }

http {

    sendfile on;

    upstream app-one {
        server app-one:1111;
    }

    upstream app-two {
        server app-two:2222;
    }

    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-Host $server_name;
    
    server {
        listen 80;
 
        location /app-one {
            proxy_pass         http://app-one:1111;
            proxy_redirect     off;
        }
    }

    server {
        listen 80;
 
        location /app-two {
            proxy_pass         http://app-two:2222;
            proxy_redirect     off;
        }
    }
}

有没有人知道如何调整配置:)
无论如何,先谢谢你的帮助。

zpqajqem

zpqajqem1#

当nginx启动时,应用程序必须已经在运行。否则nginx服务器没有启动。相应地调整了docker-compose文件:

version: '3.7'
services:
  proxy:
    image: "proxy"
    build: ./nginx-data
    ports:
    - "80:80"
    environment:
    - NGINX_PORT=80
    depends_on:
      app-one:
        condition: service_started
      app-two:
        condition: service_started
  app-one:
    image: "app-one"
    container_name: app-one
  app-two:
    image: "app-two"
    container_name: app-two

相关问题