在看該文章前,你須要對Docker有所瞭解。html
一、建立WebApp應用程序nginx
我使用的是.Net Core 1.0.1版本,建立一個MVC應用程序,並添加對Redis的引用。由於這些很基礎,也很簡單,這裏就不詳細說明了,特別提一下有關多站點會話保持問題,這裏介紹兩種方式,一種方式就是使用我博客裏所說的方法 http://www.cnblogs.com/anech/p/6873604.html,還有一種方式就是採用Nginx代理的會話保持方案。web
二、建立WebApp的Dockerfile文件redis
FROM microsoft/aspnetcore:1.0.1 ENTRYPOINT ["dotnet", "TestCentOS.dll"] ARG source=. ARG port=80 ENV ASPNETCORE_URLS http://+:$port WORKDIR /app EXPOSE $port COPY $source .
大意就是:使用microsoft/aspnetcore:1.0.1基礎鏡像建立一個新的鏡像,鏡像在運行的時候執行dotnet TestCentOS.dll命令啓動程序程序,把當前目錄下的文件複製到鏡像中,並暴露一個指定的端口,若是未指定使用默認80端口。docker
三、建立Nginx的Dockerfile文件後端
FROM nginx EXPOSE 80 COPY default.conf /etc/nginx/conf.d/
大意是:基於nginx基礎鏡像建立一個新的鏡像,對外暴露80端口,並把當前目錄下的default.conf複製到鏡像的/etc/nginx/conf.d/目錄下。app
default.conf文件內容:webapp
upstream webapp{ server weba:80 max_fails=3 fail_timeout=20s; server webb:80 max_fails=3 fail_timeout=20s; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; location / { proxy_pass http://webapp/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
這裏是對nignx進行負載配置,配置兩個應用的地址。ui
四、建立docker-compose.yml文件.net
version: '2' services: nginx: image: testnginx # build: # context: . # dockerfile: NginxDockerfile ports: - "5000:80" links: - weba - webb weba: image: testweb # build: # context: . # dockerfile: Dockerfile expose: - "80" links: - redis webb: image: testweb # build: # context: . # dockerfile: Dockerfile expose: - "80" links: - redis redis: image: redis expose: - 6379
這裏爲了方便,我先執行上邊的Dockerfile文件建立了一個.net core應用的鏡像testweb和Nginx鏡像testnginx,而後咱們在建立集羣的時候都使用這兩個鏡像。也能夠省去這一步,直接使用Dockerfile來建立,此時會建立三個鏡像,由於咱們這裏部署了兩個應用weba和webb應用和一個nginx。
這個yml文件的大意是:建立並啓動4個容器,一個nginx容器,兩個webapp容器,一個redis容器,nginx對外暴露端口80與本機的5000端口映射,nginx容器能夠訪問兩個webapp容器,兩個webapp容器均可以訪問redis容器。這樣咱們就實現了Nginx代理請求,並分發至後端兩個webapp應用,兩個webapp應用使用redis服務。
五、執行docker-compose.yml文件
docker-compose up
該命令十分強大,它將嘗試自動完成包括構建鏡像,(從新)建立服務,啓動服 務,並關聯服務相關容器的一系列操做。
此時訪問http://localhost:5000/ 即可看到效果。