詳解docker容器間通信的一種方法
以我的ghost博客為例進(jìn)行說明,我在VPS上用docker啟動了兩個ghost博客,還有一個Nginx做反向代理,將兩個域名分別指向兩個博客。
docker啟動命令
ghost:
docker run -e NODE_ENV=production --name ghost1 -v /path/to/data/ghost/ghost1/:/var/lib/ghost -d ghost docker run -e NODE_ENV=production --name ghost2 -v /path/to/data/ghost/ghost2/:/var/lib/ghost -d ghost
nginx:
docker run -p 80:80 --name nginx --link ghost1 --link ghost2 -v /path/to/data/nginx/nginx.conf:/etc/nginx/nginx.conf -d nginx
先啟動兩個ghost,然后啟動nginx。使用--link參數(shù)將容器“鏈接”到一起,此參數(shù)會在容器中加入環(huán)境變量并在/etc/hosts中插入一條容器名與IP的映射
root@fabfd4bacfda:/# cat /etc/hosts 172.17.0.3 ghost1 d19c0134011a 172.17.0.5 ghost2 0e2e66ba70e0 172.17.0.4 fabfd4bacfda
設(shè)置nginx反向代理
修改nginx.conf,在http段內(nèi)添加如下內(nèi)容
http {
server {
listen 80;
server_name www.domain1.tk domain1.tk;
location / {
proxy_pass http://ghost1:2368;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 80;
server_name www.domain2.tk domain2.tk;
location / {
proxy_pass http://ghost2:2368;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
注意proxy_pass的值proxy_pass http://ghost2:2368;。 ghost2是nginx容器/etc/hosts中的一條,是由--link參數(shù)添加進(jìn)來的。
設(shè)置完這些后,nginx就會將兩個域名的請求分別代理到兩個博客中。
補(bǔ)充
容器重啟后IP可能變化,所以直接在nginx.conf中指定IP并不是一個好方法。使用--link時hosts文件會隨著容器IP的變化更新,所以使用域名才是更容易維護(hù)的方法。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
docker logs-查看docker容器日志的實現(xiàn)
這篇文章主要介紹了docker logs-查看docker容器日志的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Centos Docker1.12 遠(yuǎn)程Rest api訪問的配置方法
這篇文章主要介紹了Centos Docker1.12 遠(yuǎn)程Rest api訪問的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-01-01
Dockerfile構(gòu)建自定義鏡像的實現(xiàn)
Dockerfile構(gòu)建鏡像的方式就目前而言是使用最為廣泛的,本文主要介紹了Dockerfile構(gòu)建自定義鏡像的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
docker容器與宿主機(jī)的數(shù)據(jù)交互方式總結(jié)
這篇文章主要給大家介紹了關(guān)于docker容器與宿主機(jī)的數(shù)據(jù)交互,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

