2017-08-03 103 views
1

Node.js中的web应用程序通过axios连接到api。如何将一个Node.js应用程序连接到Docker服务的http rest API?

import axios from 'axios' 

export function fetchList() { 
    return axios.get('https://api.website.dev/v1/posts') 
} 

该api运作良好,一切都很好。


现在,我使用docker-compose在容器中运行完全相同的nodejs web应用程序。

泊坞窗,compose.yml:

版本: “3.1”

服务:

nodejs: 
    image: node:alpine 
    working_dir: /home/app 
    restart: always 
    ports: 
     - "8000:8080" 
    volumes: 
     - ../nodejs:/home/app 
    command: ["npm", "start"] 

的Axios公司调用REST API返回一个错误:

error { Error: getaddrinfo EAI_AGAIN api.domain.dev:443 
    at Object.exports._errnoException (util.js:1024:11) 
    at errnoException (dns.js:55:15) 
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26) 
code: 'EAI_AGAIN', 
errno: 'EAI_AGAIN', 
syscall: 'getaddrinfo', 
hostname: 'api.domain.dev', 
host: 'api.domain.dev', 
port: 443, 
config: 
{ adapter 
… 

如何让nodejs应用程序连接到码头集装箱的api?搬运工集群内

回答

1

DNS服务器不知道主机api.website.dev

可以explicetelly设置该主机的IP地址点儿。尝试添加extra_hosts服务定义在docker-compose.yml

nodejs: 
    image: node:alpine 
    working_dir: /home/app 
    restart: always 
    ports: 
     - "8000:8080" 
    volumes: 
     - ../nodejs:/home/app 
    command: ["npm", "start"] 
    extra_hosts: 
     - "api.website.dev:<IP_ADDRESS> 

或者,如果你有哪些有所了解website.dev,你可以把它添加到集群泊坞窗所描述here

+0

谢谢外部DNS服务器。我试着用'api.website.dev:127.0.0.1'(因为api在本地主机上运行),但现在它执行了一个错误:连接ECONNREFUSED 127.0.0.1:443' –

+0

它发生是因为127.0.0.1它是一个本地主机。 nodejs尝试连接到nodejs容器,而不是连接到主机。尝试使用'192.168.1.33'等主机另一个IP地址添加'额外主机'。 –

+1

[这个答案](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach)可以帮助你 –

相关问题