简体   繁体   English

配置Nginx进行路由

[英]Configure Nginx for routing

I am using Nginx docker image on port 80 in my VM (address xyzw ). 我在我的VM(地址xyzw )中的端口80上使用Nginx xyzw So when I try http://xyzw in my browser, it is showing me Nginx index file. 因此,当我在浏览器中尝试http://xyzw时,它显示的是Nginx索引文件。

Now I am configuring (basically proxy passing) it for my two docker images running on same VM on ports 8081 and 8082. What I want: 现在我正在配置(基本上代理传递)它为我在端口8081和8082上的相同VM上运行的两个docker镜像。我想要的:

when I type http://x.y.z.w/a it should go to http://x.y.z.w:8081
when I type http://x.y.z.w/b it should go to http://x.y.z.w:8082

For this, I changed a portion in my conf file: 为此,我在conf文件中更改了一部分:

     location /a {
        rewrite ^/a(.*) /$1 break;
        proxy_pass http://x.y.z.w:8081 ;
    }

    location /b {
        rewrite ^/b(.*) /$1 break;
        proxy_pass http://x.y.z.w:8082 ;
    }

It is working as expected. 它按预期工作。 But as all the images are in same machine (have same IP), I want to use localhost instead of xyzw . 但由于所有图像都在同一台机器上(具有相同的IP),我想使用localhost而不是xyzw But it is not working with localhost . 但它不适用于localhost

Basically, I don't want to use the hardcoded IP (xyzw) in links, as the IP can change in the future. 基本上,我不想在链接中使用硬编码IP(xyzw),因为IP将来可能会发生变化。

Is there any way, Nginx can know the variable IP on which it is running and I may use that IP. 有没有办法,Nginx可以知道它运行的变量IP,我可以使用该IP。 Or how can it work with localhost with some modification? 或者如何通过一些修改与localhost一起使用?

You can't use localhost to address another docker container, since it refers to the loopback of the container and not of the host. 您不能使用localhost来寻址另一个docker容器,因为它指的是容器的loopback而不是主机的loopback As @Tuan suggested, you can link ( https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/ ) containers, so they can communicate via their names. 正如@Tuan建议的那样,您可以linkhttps://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/ )容器,以便他们可以通过他们的名字进行通信。 Eg: 例如:

docker run --rm -ti --name backend nginx:latest
docker run --rm -ti --name proxy --link backend:backend nginx:latest

Now proxy knows about backend . 现在proxy知道backend

I just replaced every occurrence of xyzw in my nginx.conf with $host and it is working fine. 我刚用$host替换了我的nginx.conf每次出现的xyzw ,它运行正常。

For example, instead of proxy_pass http://xyzw:8081 ; 例如,而不是proxy_pass http://xyzw:8081 ; ,

wrote it proxy_pass http://$host:8081 ; 把它写成了proxy_pass http://$host:8081 ;

Now if my IP ( xyzw ) changes, it does not effect to my applications. 现在,如果我的IP( xyzw )发生变化,它对我的​​应用程序没有影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM