4

I am trying to configure a nginx Docker container to serve the Angular application on its root path (which works so far) and make the backend via a proxy on /api available.

I've read multiple threads on Stackoverflow and some blogs, but no configuration worked so far. If I call my app on / the Angular app works. When I try to call /api on the same url it gets redirected to / and shows no content -- I guess the Angular router got some route it cannot handle. But Nginx should catch that route before the Angular app gets called. How do I do that?

I am not sure what is wrong. Do you see the error in my config?

server {
  listen 80;
  sendfile on;
  default_type application/octet-stream;

  gzip on;
  gzip_http_version 1.1;
  gzip_disable      "MSIE [1-6]\.";
  gzip_min_length   256;
  gzip_vary         on;
  gzip_proxied      expired no-cache no-store private auth;
  gzip_types        text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  gzip_comp_level   9;

  location / {
    root /usr/share/nginx/html;
    try_files $uri $uri/ /index.html =404;
  }
  
  location /api/ {
    proxy_pass http://host.docker.internal:8080/api/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}

Edit1: I found one issue: the container was not able to reach the api-server. I changed it in the config to host.docker.internal which is accessible via docker ci. But I am still not able to call /api on the nginx container. I now get a 404.

3
  • 1
    Do you call only /api or /api/<some resource>? Your api location block gets triggered with a trailing slash (/api/) not /api. Jan 26, 2022 at 13:31
  • @RobertKeck I call it with something behind it. So /api/Names for example.
    – Apollo
    Jan 26, 2022 at 13:37
  • I think I have found the issue... I was in a different folder for another frontend app which I stopped and started. The config above works, I was just in a wrong folder... Ouch.
    – Apollo
    Jan 26, 2022 at 13:53

2 Answers 2

2

I would use the syntax below to let Nginx know this comes before your generic location location /.

location ^~ /api/ { }

You can read more here -> https://www.journaldev.com/26342/nginx-location-directive

0

As it turns out the config above works, I was in the wrong folder for another project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.