skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

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


  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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search