1. 程式人生 > >Spring Cloud基於Docker進行打包部署4-容器間的連線和通訊(單主機環境)

Spring Cloud基於Docker進行打包部署4-容器間的連線和通訊(單主機環境)

---
elasticsearch:
  image: elasticsearch:latest
  command: elasticsearch -Des.network.host=0.0.0.0
  ports:
    - "9200:9200"

logstash:
  image: logstash:latest
  command: logstash -f logstash.conf
  ports:
    - "5000:5000"
  links:
    - elasticsearch

連線不同docker-compose.yml中的容器,需要使用external_links引數,設定目標容器的名字。

If you want to link a container inside of the docker-compose.yml to another container that was not included in the same docker-compose.yml or started in a different manner then you can use external_links

 and you would set the link to the container's name. Like this:

---
logstash:
  image: logstash:latest
  command: logstash -f logstash.conf
  ports:
    - "5000:5000"
  external_links:
    - my_elasticsearch_container

建議把應用放在同一個docker-compose.yml檔案中

I would suggest the first way unless your use case for some reason requires that they cannot be in the same docker-compose.yml

2、51CTO網站相關資料:

容器定義在同一個docker-compose.yml檔案中的情況與上邊一樣,來看在不同yml檔案中的情況:

方式:讓需要連結的容器同屬一個外部網路

我們還是使用nginx映象來模擬這樣的一個情景:假設我們需要將兩個使用Docker Compose管理的nignx容器( test1 和 test2 )連結起來,使得 test2 能夠訪問 test1 中提供的服務,這裡我們以能ping通為準。

首先,我們定義容器 test1 的 docker-compose.yml 檔案內容為:

version: "3" 
services: 
  test2: 
  image: nginx 
  container_name: test1 
  networks: 
    - default 
    - app_net 
networks: 
  app_net: 
  external: true 

容器 test2 內容與 test1 基本一樣,只是多了一個 external_links ,需要特別說明的是: 最近釋出的Docker版本已經不需要使用external_links來連結容器,容器的DNS服務可以正確的作出判斷 ,因此如果你你需要相容較老版本的Docker的話,那麼容器 test2 的 docker-compose.yml檔案內容為