2017-08-03 101 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)可以幫助你 –

相關問題