此问题在此处已有答案:
"Unknown host" error calling containerized backend from frontend(1个答案)
26天前关闭。
我在写一个应用程序。我写.net作为后端,Angular作为前端。对接的时候,我把我的前端应用程序放在nginx里面。Dockerfile是这样的
FROM node:20.10-alpine AS build
WORKDIR /app
COPY package*.json .
RUN npm install
RUN npx ngcc --properties es2023 browser module main --first-only --create-ivy-entry-points
COPY . .
RUN npm run build --prod
FROM nginx:stable
COPY --from=build /app/dist/librari-fy/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
字符串
nginx.conf如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name http://backend:80;
root /usr/share/nginx/html/browser;
index index.html index.htm;
include /etc/nginx/mime.types;
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 / {
try_files $uri $uri/ /index.html;
add_header Access-Control-Allow-Origin *;
add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;
}
}
}
型
Docker-compose文件:
version: '3.8'
services:
postgres:
image: postgres:16-alpine
container_name: postgredatabase
restart: always
environment:
POSTGRES_PASSWORD: UArA0CGd5y1g5sE7U0OH
POSTGRES_USER: libraryadmin
POSTGRES_DB: Library
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- app_internal_network
healthcheck:
test: pg_isready
interval: 10s
timeout: 60s
retries: 5
start_period: 80s
backend:
image: sahinyakici/librarybackend:latest
restart: always
container_name: backend
depends_on:
postgres:
condition: service_healthy
networks:
- app_internal_network
ports:
- "8080:80"
frontend:
container_name: librarify
image: sahinyakici/librarify:latest
restart: always
depends_on:
- backend
networks:
- app_internal_network
ports:
- 80:80
expose:
- 80
volumes:
postgres_data:
networks:
app_internal_network:
driver: bridge
型
应用程序运行成功,但我在网站的控制台中得到以下错误:“Failed to load resource:net::ERR_NAME_NOT_RESOLVED”。如果我进入UI容器并尝试使用curl,我可以从后端获取数据。您认为是什么问题?
Error screenshotError2Error3
我试着从容器中使用 curl 。
1条答案
按热度按时间w41d8nur1#
前端代码在客户端执行,这意味着浏览器处理代码,而不是NGINX Web服务器。当您请求前端容器时,NGINX服务器返回您网站的HTML,CSS和JavaScript文件,这些文件由浏览器解释。
因此,您的浏览器,通过扩展您的计算机,将是请求后端API的人。因此,在前端中配置的后端URL应该是
http://localhost:8080
而不是http://backend
您的NGINX服务器应该只提供前端文件。将
server_name
修复为localhost
,并将前端代码中的后端URL修复为http://localhost:8080