简体   繁体   English

无法在docker-compose中使用主机名访问rails-api后端

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

I am trying to make a rails-api backend and react frontend website with docker-compose. 我正在尝试制作一个rails-api后端并使用docker-compose反应前端网站。 But i couldn't send get request to rails-api backend with axios with my hostname (stated in docker-compose). 但是我无法使用主机名(在docker-compose中声明)的axios将get请求发送到rails-api后端。 I can access backend through localhost but that will be a problem (i assume) when i deploy the multi-container app to aws elastic beanstalk. 我可以通过localhost访问后端,但是当我将多容器应用程序部署到AWS Elastic Beanstalk时,这将是一个问题(我认为)。

I am trying to access values like this: 我正在尝试访问这样的值:

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

This is in my docker-compose.yml: 这是在我的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

I get this error instead 我得到这个错误

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

Thank you in advance. 先感谢您。 Any help is most welcomed. 任何帮助都非常欢迎。

I managed to get some clue from a stack overflow post. 我设法从堆栈溢出帖子中得到一些线索。 Here Unable to have Docker containers communicate with each other . 在这里, 无法使Docker容器彼此通信 As the answer in the post suggests, I had to set up a nginx container to proxy (redirect) the request. 正如帖子中的答案所建议的,我必须设置一个nginx容器来代理(重定向)请求。

I changed my axios request to: 我将axios请求更改为:

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

And made a nginx container with a default.conf file like such: 并使用以下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;  
    }
}

Hope this information is able to help someone who is stuck. 希望此信息能够帮助陷入困境的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM