我有一個問題,我在 docker 的 buildstep 中構建我的 reactjs 應用程式,然后使用 nginx 運行它。但是我無法讓它能夠連接到我在另一個容器中運行的 api
我的 docker-cmpose.yml 的相關部分在這里
api:
build:
dockerfile: Dockerfile
context: "./api"
depends_on:
- mysql_db
volumes:
- /app/node_modules
- ./api:/app
environment:
<<: *common-variables
MYSQL_HOST_IP: mysql_db
networks:
- my-network
frontend:
depends_on:
- api
stdin_open: true
environment:
API_URL: http://api:3030/v1
build:
dockerfile: Dockerfile
context: ./frontend
ports:
- "8090:80"
volumes:
- /app/node_modules
- ./frontend:/app
networks:
- my-network
networks:
my-network:
name: my-network
我的 Dockerfile 中的相關位是
COPY package.json ./
COPY ./ ./
RUN npm i && npm run build
# production environment
FROM nginx:stable-alpine
WORKDIR /app
COPY --from=build /app/build /usr/share/nginx/html
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
最后在我的 default.conf for ngnx 我有
upstream api {
server api:3030;
}
server {
listen 80;
listen [::]:80;
root /usr/share/nginx/html;
index index.html index.htm index.nginx-debian.html;
server_name xxxx.com www.xxxx.com
location / {
try_files $uri $uri/ =404;
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://api;
}
}
我遇到的問題是它無法解決 api

請任何人都可以幫我解決在其容器中運行的 api 的 ip/url 嗎?
提前致謝
uj5u.com熱心網友回復:
React 應用程式在瀏覽器中運行,它不能使用任何 Docker 網路功能。特別是,由于它在瀏覽器中運行,它無法決議api主機名,主機名只存在于運行在同一個 Compose 網路上的容器中,而您的瀏覽器不在容器中。
您已經將 Nginx 設定為代理/api到后端應用程式,我將使用該路徑。您可能可以設定類似API_URL: /api/v1沒有主機部分的東西。您的瀏覽器會將其解釋為僅路徑的相對 URL,并使用運行應用程式的主機和埠。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412684.html
標籤:
