簡體   English   中英

無法在docker-compose中使用主機名訪問rails-api后端

[英]Can't access rails-api backend with hostname in docker-compose

我正在嘗試制作一個rails-api后端並使用docker-compose反應前端網站。 但是我無法使用主機名(在docker-compose中聲明)的axios將get請求發送到rails-api后端。 我可以通過localhost訪問后端,但是當我將多容器應用程序部署到AWS Elastic Beanstalk時,這將是一個問題(我認為)。

我正在嘗試訪問這樣的值:

const value = await axios.get('http://website:3000/api/v1/examples');

這是在我的docker-compose.yml中:

version: '2'

services:
  website:
    depends_on:
      - 'postgres'
      - 'redis'
    build: .
    ports:
      - '3000:3000'
    volumes:
      - '.:/app'
    env_file:
      - '.env'
  frontend:
    build:
      context: ./../atwo-react-2
      dockerfile: Dockerfile.dev
    ports:
      - '3001:3001'
    volumes:
      - ./../atwo-react-2:/app
    depends_on:
      - website

我得到這個錯誤

在Google控制台中GET http://website:3000/api/v1/examples net::ERR_NAME_NOT_RESOLVED

先感謝您。 任何幫助都非常歡迎。

我設法從堆棧溢出帖子中得到一些線索。 在這里, 無法使Docker容器彼此通信 正如帖子中的答案所建議的,我必須設置一個nginx容器來代理(重定向)請求。

我將axios請求更改為:

const value = await axios.get('/api/v1/examples');

並使用以下default.conf文件制作了一個nginx容器:

upstream website {
    server website:3000;
}

upstream frontend {
    server frontend:3001;
}

server {
    listen 80;

    location / {
        proxy_pass http://frontend;
    }

    location /sockjs-node {
        proxy_pass http://frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }

    location /api {
        proxy_pass http://website;  
    }
}

希望此信息能夠幫助陷入困境的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM