'Unable to serve static files with Nginx proxy and multiple containers

I have multiple node js apps running in Docker containers that is able to serve the static files which are bundled in the Docker image. So for example if I go directly and load the container (without going via nginx) http://app01.local:8001, everything loads fine.

Once I bring in Nginx to proxy multiple containers, this is where the problem begins. I want to proxy pass 2 containers as is and let the node js serve the static files but the requests for the files return 404. To workaround this issue, I created volumes so that nginx is able to see the static files from the nodejs containers.

What I want is something like this to work:

upstream app01 {
  server app01:8001
}

upstream app02 {
  server app02:8002
}

server {
  listen 80;
  server_name myapp.local;

  location / {
     proxy_pass http://app01;
  }


   location /abc/def {
     proxy_pass http://app02;
   }
}

Doing something like this snippet below of course works and static files load but I need it to proxy to multiple containers:

upstream app01 {
  server app01:8001
}

server {
  listen 80;
  server_name myapp.local;

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

When I use a prefix location, then I have to specify location for my static files.

My nginx config actually looks like this:

upstream app01 {
  server app01:8001
}

upstream app02 {
  server app02:8002
}

server {
  listen 80;
  server_name myapp.local;

  location / {
     proxy_pass http://app01;
  }

  location /static {
    alias /opt/app01/static;
  }

  location /abc/def {
    proxy_pass http://app02;

  # I'm not sure what to do here, as app02 also has static files which is also served as myapp.local/static
  }
 
  # If I add this, I'd get /static is outside of /abc/def error
  #  location /static {
  #    alias /opt/app02/static;
  # }
   
}

If I go to myapp.local/abc/def, it route to the correct app02 container but none of the static files will load. If I can get away from using the volumes and specifying aliases, then that would be ideal (see first code block).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source