Docker-Compose 一键部署Ningx+.Net Core+Redis集群

在看该文章前,你需要对Docker有所了解。

1、创建WebApp应用程序

 我使用的是.Net Core 1.0.1版本,创建一个MVC应用程序,并添加对Redis的引用。因为这些很基础,也很简单,这里就不详细说明了,特别提一下有关多站点会话保持问题,这里介绍两种方式,一种方式就是使用我博客里所说的方法 http://www.cnblogs.com/anech/p/6873604.html,还有一种方式就是采用Nginx代理的会话保持方案。

2、创建WebApp的Dockerfile文件

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端口。

3、创建Nginx的Dockerfile文件

FROM nginx
EXPOSE 80
COPY default.conf /etc/nginx/conf.d/

  大意是:基于nginx基础镜像创建一个新的镜像,对外暴露80端口,并把当前目录下的default.conf复制到镜像的/etc/nginx/conf.d/目录下。

default.conf文件内容:

   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进行负载配置,配置两个应用的地址。

4、创建docker-compose.yml文件

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服务。

5、执行docker-compose.yml文件

docker-compose up 

 该命令十分强大,它将尝试自动完成包括构建镜像,(重新)创建服务,启动服 务,并关联服务相关容器的一系列操作。  

此时访问http://localhost:5000/ 便可看到效果。

 

文章出处:http://www.cnblogs.com/anech/p/6873828.html

posted @ 2017-05-18 15:57  anech  阅读(1357)  评论(0编辑  收藏  举报