How to connect back-end with front-end using ngnix in Kubernetes
Solved it using this nginx.conf
upstream purser { server purser.default.svc.cluster.local:3030;}server { listen 4200; location /api { proxy_pass http://purser; } location / { root /usr/share/nginx/html/purser; index index.html index.htm; try_files $uri $uri/ /index.html =404; }}
and calling backend from frontend using BACKEND_URL = window.location.protocol + '//' + window.location.host + '/api/'
Explanation:Frontend when it requires data from backend calls itself at path /api
, nginx finds this path and according to configuration forwards it to backend kubernetes service purser.default.svc.cluster.local:3030
using proxy_pass
@Kaladin your approach was almost there, but I think there is something missing.
What I did was
upstream gateway { server gateway-cip-service:3000;}server { listen 80; location /api { rewrite /api/(.*) /$1 break; proxy_pass http://gateway; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; }}
The biggest headache was to find out the proxy header upgrade, such a pain.
Consider that in my backend my routes do not have an "api" prefix, that is why I use "rewrite /api/(.*) /$1 break;" to take only whatever that comes after /api/ Otherwise, you can avoid that line of code.