使用docker部署Vue前端和.net后端,前端未解析后端容器名称



我正试图在前端部署Vue应用程序,在后端部署.net核心api。使用docker compose文件,我已经能够旋转网络和容器,但我很难让它们通信。然而,我对docker还很陌生,我知道Vue应用程序dockerfile使用Nginx库来为web应用程序提供信息,但这似乎会影响网络通信,因为前端容器没有解析后端容器名称,尽管应该解析,因为它们与默认的网桥驱动程序在同一个虚拟专用网络中。当在前端容器中执行bash-shell并对后端容器进行卷曲时,我确实得到了正确的响应。

我确实尝试将后端容器暴露给主机,然后使用服务器IP从前端访问它,这确实有效。然而,我希望不必以这种方式暴露我的api,并希望尽可能通过docker虚拟专用网络使其工作。

我在前端尝试的示例url遇到了一个名称未解析的错误:littlepigg-api/api或littlepiggi-api:5000/api

前端Dockerfile

FROM node:14.18-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY ./ .
RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

后端Dockerfile

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 5000
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["LittlePiggy.Api/LittlePiggy.Api.csproj", "LittlePiggy.Api/"]
RUN dotnet restore "LittlePiggy.Api/LittlePiggy.Api.csproj"
COPY . .
WORKDIR "/src/LittlePiggy.Api"
RUN dotnet build "LittlePiggy.Api.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "LittlePiggy.Api.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "LittlePiggy.Api.dll"] 

Docker组成文件

version: '3'
services:
front:
container_name: littlepiggy-front
image: josh898/angie-app-front:latest
ports:
- 80:80
networks:
- littlepiggy
depends_on:
- api
api:
container_name: littlepiggy-api
image: josh898/angie-app-backend:latest
networks:
- littlepiggy
networks:
littlepiggy:
driver: bridge

您需要配置Nginx,以便将匹配/api路由的请求传递到后端服务。

如果您创建一个类似于这样的nginx配置文件,称为nginx.conf,并将其放置在前端目录中

server { 
listen 80;
location / {
index index.html;
root /usr/share/nginx/html;
try_files $uri $uri/ $uri.html =404;
}
location /api/ {
proxy_pass http://littlepiggy-api/;
}
}

然后通过将前端Dockerfile更改为将其复制到前端容器中

FROM node:14.18-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY ./ .
RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

然后请求http://localhost/api/xxxx应传递到后端并请求http://localhost/index.html应直接由Nginx集装箱提供服务。

相关内容

  • 没有找到相关文章

最新更新