使用jwilder nginx-proxy,如何将子目录url代理传递到特定容器? [英] With jwilder nginx-proxy, how to proxypass a subdirectory url to a specific container?

查看:108
本文介绍了使用jwilder nginx-proxy,如何将子目录url代理传递到特定容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jwilder/nginx-proxy 做反向代理.我尝试将http://localhost:8000/api重定向到特定的php服务.

I use jwilder/nginx-proxy to make a reverse proxy. I try to redirect http://localhost:8000/api to a specific php service.

目录结构:

.
+-- docker-compose.yml
+-- nginx
+-- nodejs
|   +-- index.js
|   +-- …
+-- php
|   +-- api

docker-compose.yml:

docker-compose.yml:

version: "3.1"

services:

  nginx-proxy:
    image: jwilder/nginx-proxy:alpine
    ports:
      - "8000:80"
    volumes:
      - ./php:/srv/www
      - /var/run/docker.sock:/tmp/docker.sock:ro

  nodejs:
    image: node:alpine
    environment: 
      - NODE_ENV=production
      - VIRTUAL_HOST=localhost
      - VIRTUAL_PORT=8080
    expose:
      - "8080"
    working_dir: /home/app
    restart: always
    volumes:
      - ./nodejs:/home/app
    command: ["node", "index.js"]

  php:
    image: php:apache
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - ./php:/var/www/html

这对于nodejs服务正常工作.

This works fine for the nodejs service.

现在,我想将对http://localhost:8000/api的调用重定向到php服务.我想我必须在nginx conf中添加以下内容:

Now, I would like to redirect calls to http://localhost:8000/api to the php service. I imagine that I have to add to the nginx conf something like:

server {
  location /api {
    proxy_pass http://php:80/api;
    proxy_set_header Host $host;
  }
}

此功能未内置在库中. 那么,我该如何实现呢?

This feature is not built into the lib. So, how can I achieve that?

推荐答案

一种方法是为php应用提供自己的虚拟主机:

One approach is to give the php app its own virtual host:

  php:
    image: php:apache
    environment:
      - VIRTUAL_HOST=api.localhost
    volumes:
      - ./php:/var/www/html

然后,它将是可访问的:

Then, it will be accesible as this:

curl -H 'Host: api.localhost' http://localhost:8000/api

几乎可以用任何一种语言来设置标题.或者,为避免设置自定义标头,您可以将该DNS添加到您的/etc/hosts文件中:

Setting the header can be achieved in practically any language. Or to avoid setting custom header, you can add that DNS to your /etc/hosts file:

127.0.0.1 api.localhost

因此,您可以像这样卷曲:

So you can curl as this:

curl -H http://api.localhost:8000/api

这是设置自定义标头的方式,例如在节点中:

This is how set custom headers, for example in node:

var request = require('request')

var formData = {}

request({
    headers: {
      'Host': 'api.localhost'
    },
    uri: 'http://localhost:8080',
    method: 'POST'
  }, function (err, res, body) {
      console.log("it works")
      console.log(res)
    }
)

但是,我建议您采用/etc/hosts方法,该方法在生产环境(DNS服务器)中应该等效.因此,您无需触摸节点代码.

But, I recommend you to go for the /etc/hosts approach, that should has an equivalent in production environment (a DNS server). So you don't need to touch node code.

这篇关于使用jwilder nginx-proxy,如何将子目录url代理传递到特定容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆