我有一个应用程序,其中包括一个前端和后端。两者都应该在Docker compose中的容器中一起运行。后端工作正常,在开发前端时没有引起任何问题。现在我们来到前台。前端是一个使用Angular路由的Angular应用程序。在开发过程中,我总是使用“ng serve”进行开发,并使用以下proxy-conf.json访问API:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
但是,现在我也想在容器中运行我的前端。为此,我使用以下Dockerfile对Angular应用程序进行了dockerized。我可以访问应用程序,但每个API调用都不起作用。
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
这是我的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-composite.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
我读过很多关于stackoverflow的文章,但是没有一个是有目的的。如何从我的应用访问后端?
谢谢你的帮助!
1条答案
按热度按时间4nkexdtk1#
必须在nginx.conf上添加一个proxy_pass,如下所示:
我认为在你的开发环境中,你可以调用像这样的API
http://localhost:3000/api
。在nginx.conf tell中添加此位置到服务器:* “当在http://localhost:3000/api/上收到请求时,将其重定向到${API_HOST}"*
${API_HOST}必须设置为后端,在本例中为
http://backend:3000/
,API后缀由位置添加。其他设置基本上是将关于原始请求的信息添加到标头中。