简体   繁体   中英

Nginx in Docker Swarm to implement path based Routing

I am trying to use nginx to act as a proxy to two Swarm services (called service1 and service2) by using path based routing.

This is how the services are run:

docker service create --name service1 -p 8080:80 --replicas 3 --network mynet httpd

docker service create --name service2 -p 8081:80 --replicas 3 --network mynet nginx

mynet is an overlay network.

This is my dockerfile.

FROM nginx

RUN rm /etc/nginx/conf.d/*
COPY backend.conf /etc/nginx/conf.d/

EXPOSE 80

This is backend.conf.

upstream service1 {
    server service1;
}

upstream service2 {
    server service2;
}

server {
    listen 8000;


    location / {
        proxy_pass http://service1;
    }

    location /service2 {
        proxy_pass http://service2;
    }
    
}

This image is built using standard dockerbuilt command and the image is called nginxelb.

docker build -t nginxelb .

This is how I run the proxy service.

docker service create --name nginx-app -p 80:8000 --replicas 3 --network mynet nginxelb

The service runs with 3 replicas as I expected.

When I run curl localhost, I get this output:

<html><body><h1>It works!</h1></body></html>

This is great.

But when I run curl localhost/service2, the output is

<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.19.2</center>
</body>
</html>

I am trying to not hardcode the IP address of the host and use service name as DNS resolver. It seems work fine for the root path but not for the other path.

My apps are running on Amazon Linux 2 where I manually installed docker. Docker version is Docker version 19.03.2, build 6a30dfc.

What am I doing wrong?

Got this working after a tweak to the backend.conf file. Added this line of code:

rewrite ^/service2(.*) /$1 break;

This is based on another post .

The updated backend.conf file looks like this:

upstream service1 {
    server service1;
}

upstream service2 {
    server service2;
}

server {
    listen 8000;


    location / {
        proxy_pass http://service1;
    }

    location /service2 {
        rewrite ^/service2(.*) /$1 break;
        proxy_pass http://service2;
    }
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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