I have an app which consists of a frontend and a backend. Both should run together in a container in a Docker compose. The backend works fine and has not caused any problems while developing the frontend. Now we come to the frontend. The frontend is an Angular app which uses Angular routing. While developing I always developed with "ng serve" and used the following proxy-conf.json to access the API:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
However, now I want to run my frontend in a container as well. For this I have dockerized the Angular app with the following Dockerfile. I can access the App, but every API-Call does not work.
FROM node:16-alpine AS build
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
# Serve Application using Nginx Server
FROM nginx:alpine
COPY --from=build /app/dist/my-app/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
This is my nginx.conf:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html;
}
}
My docker-compose.yml:
version: '3'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- 3000:3000
frontend:
build:
context: ./frontend/my-app
dockerfile: Dockerfile
ports:
- 8080:80
depends_on:
- backend
I have read many stackoverflow articles,however,nonew ar purposeful. How can I access the backend from my app?
Thanks for your help!
You must add a proxy_pass on nginx.conf like this:
location /api/ {
proxy_pass ${API_HOST};
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass_request_headers on;
}
I think on your dev environment you call an API like this http://localhost:3000/api.
Adding this location on nginx.conf tell to the server: "when coming a request on http://localhost:3000/api/ then redirect it to ${API_HOST}"
The ${API_HOST} must set to the backend, in this case, is http://backend:3000/ the API suffix is added by the location.
The other settings basically add to the headers the infos about the original request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With