node.js-Nginx反向代理:如何通过子域访问不同的容器?

前端之家收集整理的这篇文章主要介绍了node.js-Nginx反向代理:如何通过子域访问不同的容器? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这就是我使用Nginx配置反向代理的方式.有运行nodeJS应用程序的docker容器(app1,app2,…)

这样,我通过localhost:8080指向docker容器app1 nodeJS应用程序,并通过localhost:8081指向app2.

但是我想通过子域调用应用程序而不使用端口,我不知道如何实现.我也认为我搞砸了港口…

app1.localhost应该指向app1,而app2.localhost应该指向app2.

Nginx.conf

http {
  sendfile on;

  upstream docker-app1 {
    server app1:80;
  }

  upstream docker-app2 {
    server app2:80;
  }

  server {
    listen 8080;
    server_name app1.localhost;
    location / {
      proxy_pass         http://docker-app1;
      proxy_redirect     off;
      proxy_buffering    off;
      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;
      #proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    }
  }

  server {
    listen 8081;
    server_name app2.localhost;
    location / {
      proxy_pass         http://docker-app2;
      proxy_redirect     off;
      proxy_buffering    off;
      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;
      #proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    }
  }
}

docker-compose.yml

version: '3.3'
services:
  Nginx:
    container_name: 'Nginx'
    image: 'Nginx:1.13.5'
    restart: 'always'
    ports:
      - '80:80'
      - '8080:8080'
      - '8081:8081'
      - '443:443'
    volumes:
      - './Nginx/conf/Nginx.conf:/etc/Nginx/Nginx.conf:ro'

  app1:
    container_name: app1
    build: ./app1
    restart: always
    ports:
      - '3001:80'

  app2:
    container_name: app2
    build: ./app1
    restart: always
    ports:
      - '4200:80'

更新:由于Sergiu为反向代理提供了很好的链接,因此我使用新配置更新了该帖子;问题还是一样

最佳答案
代替自定义Nginx,使用jwilder/nginx-proxy应该足够了:

version: '3.3'
services:
  Nginx:
    image: jwilder/Nginx-proxy
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro

  app1:
    container_name: app1
    build: ./app1
    restart: always
    environment:
      VIRTUAL_HOST: app1.localhost
    ports:
      - 80

  app2:
    container_name: app2
    build: ./app1
    restart: always
    environment:
      VIRTUAL_HOST: app2.localhost
    ports:
      - 80

然后将其放在您的计算机的/ etc / host中:

127.0.0.1 app1.localhost
127.0.0.1 app2.localhost

用作:

curl -i app1.localhost

jwilder / Nginx-proxy将神奇地读取每个容器中的VIRTUAL_HOST环境变量(通过docket API),然后相应地设置其配置文件.

猜你在找的Nginx相关文章