Search code examples
dockerrestnginxdocker-composereverse-proxy

Nginx API Gateway in Docker Compose


(Disclaimer: I've seen a lot of version of this question asked on here but none seem to really answer my question.)

I want to use NGINX as an API Gateway to route requests to microservice APIs in docker-compose.

For my sample app, I have two microservice APIs (A and B). Any request endpoint that starts with /a should go to API-A and any request endpoint that starts with /b should go to API-B.

Some issues I've had are:

  • I want paths like /a/foo/bar to match API-A but not /ab/foo
  • I want routing to work regardless of whether or not the path ends in a / (aka both /a/foo and /a/foo/ work)

My docker-compose file looks like this:

version: "3.8"
services:
  gateway:
    build:
      context: ./api-gw
    ports:
      - 8000:80
  apia:
    build:
      context: ./api-a
    ports:
      - 8000
  apib:
    build:
      context: ./api-b
    ports:
      - 8000

and my sample NGINX config file looks like this:

server {
    listen       80;
    server_name  localhost;

    location ^~ /a {
       proxy_pass   http://apia:8000/;
    }

    location ^~ /b {
       proxy_pass   http://apib:8000/;
    }

}

How can I setup my NGINX config to properly route my requests?

Thanks for your help!


Solution

  • you need to change your Nginx regex rules to these :

    match for Api-A :

    ^a(\/.*)?
    

    match for Api-B :

    ^b(\/.*)?