8天入門docker系列 —— 第五天 使用aspnetcore小案例熟悉容器互聯和docker-compose一鍵部署

 

  這一篇繼續完善webnotebook,若是你讀過上一篇的內容,你應該知道怎麼去掛載webnotebook日誌和容器的遠程訪問,可是這些還遠不夠,webnotebook前端

總要和一些數據庫打交道吧,好比說mysql,mongodb,redis,一般狀況下這些存儲設備要麼是以容器的方式承載,要麼是由DBA在非容器環境下統一管理。node

 

一:webnotebook鏈接容器redismysql

       咱們作一個小案例,把網站的全部PV記錄到redis中,webnotebook前端顯示當前你是 xxx 位用戶,案例不重要,重要的是怎麼去實現容器互聯。nginx

 

      在docker hub 上去找redis的官方鏡像,具體redis該如何合理配置這裏我就無論了,用最簡單的一條docker run 跑起來再說。git

[root@localhost data]# docker run --name some-redis -d redis
Unable to find image 'redis:latest' locally
latest: Pulling from library/redis
6ae821421a7d: Pull complete 
e3717477b42d: Pull complete 
8e70bf6cc2e6: Pull complete 
0f84ab76ce60: Pull complete 
0903bdecada2: Pull complete 
492876061fbd: Pull complete 
Digest: sha256:dd5b84ce536dffdcab79024f4df5485d010affa09e6c399b215e199a0dca38c4
Status: Downloaded newer image for redis:latest
ed07890700a5cdb7d737a196c28009a9d1b08de35f55d51f53c80e6cfe6ba199
[root@localhost data]# 
[root@localhost data]# 
[root@localhost data]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS               NAMES
ed07890700a5        redis               "docker-entrypoint.s…"   About a minute ago   Up About a minute   6379/tcp            some-redis

    

    接下來安裝 StackExchange.Redis,在Index這個Action中將當前的訪問做爲一個PV記錄到redis中,不過下面的代碼要注意一點的就是,爲了去訪問redis,github

這裏我採用了redis.webnotebook.com 去映射到redis容器的ip,映射關係能夠在建立容器的時候自動追加到 /etc/hosts 中,每一次訪問都執行一次Increment自web

增操做。redis

   public class HomeController : Controller
    {
        public static Logger logger = LogManager.GetLogger("SimpleDemo");
        public static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("redis.webnotebook.com:6379");

        /// <summary>
        /// 讀取mongodb數據數據
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            var db = redis.GetDatabase();

            var num = db.StringIncrement("count");

            ViewData["num"] = num;

            return View();
        }
    }

   

     在UI上,展現下你當前是多少位訪客,就是這樣。sql

<div class="text-center">
    <h1 class="display-4">您是當前 @ViewData["num"]  位訪客</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

     

     而後你就能夠docker build,完了以後docker run時經過 --link  some-redis:redis.webnotebook.com  去指定一下就行了,some-redis是redis容器的名字,mongodb

redis.webnotebook.com 是這個some-redis別名,這樣就方便的實現了 redis.webnotebook.com和容器ip的映射關係。

[root@localhost publish]# docker run -d --name webnotebook -p 8080:8080 --link some-redis:redis.webnotebook.com huangxincheng/webnotebook:v1
b931e040de26c4bfc0b49cbc8e626cdcb30ad9bdff523f623c0a2d6c50899a81
[root@localhost publish]# 
[root@localhost publish]# 
[root@localhost publish]# docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                    NAMES
b931e040de26        huangxincheng/webnotebook:v1   "dotnet WebNotebook.…"   2 seconds ago       Up 2 seconds        0.0.0.0:8080->8080/tcp   webnotebook
ed07890700a5        redis                          "docker-entrypoint.s…"   27 minutes ago      Up 27 minutes       6379/tcp                 some-redis

       有些人可能就好奇了,到底webnotebook容器內的/etc/hosts真的修改了嗎? 接下來你能夠經過 docker exec 到webnotebook容器去看一下就好啦,

從下面標紅的地方能夠看到,172.17.0.2 已經和 xxx.com 作了映射。

[root@localhost publish]# docker exec -it webnotebook /bin/bash
root@b931e040de26:/data# cat /etc/hosts
127.0.0.1    localhost
::1    localhost ip6-localhost ip6-loopback
fe00::0    ip6-localnet
ff00::0    ip6-mcastprefix
ff02::1    ip6-allnodes
ff02::2    ip6-allrouters
172.17.0.2    redis.webnotebook.com ed07890700a5 some-redis
172.17.0.3    b931e040de26
root@b931e040de26:/data# 

 

     回到文章開頭的問題,若是redis是在遠程宿主機上部署的,那個人webnotebook容器該怎麼訪問呢?你可能會說,直接經過ip訪問便可,可是爲了保持

統一性,我仍是但願經過redis.webnotebook.com 這個域名進行訪問,也就是說怎麼去把這個映射關係追加到容器中呢?可使用-- add-host來實現。

[root@localhost publish]#  docker run -d --name webnotebook -p 8080:8080 --add-host redis.webnotebook.com:172.17.0.2 huangxincheng/webnotebook:v1
91e7d9c1b575cc34ae98eebfc437d081b852f450104e2b368f898299852b0f18
[root@localhost publish]# docker exec -it webnotebook /bin/bash
root@91e7d9c1b575:/data# cat /etc/hosts
127.0.0.1    localhost
::1    localhost ip6-localhost ip6-loopback
fe00::0    ip6-localnet
ff00::0    ip6-mcastprefix
ff02::1    ip6-allnodes
ff02::2    ip6-allrouters
172.17.0.2    redis.webnotebook.com
172.17.0.3    91e7d9c1b575
root@91e7d9c1b575:/data# 

   

二:docker-compose 容器編排

      目前咱們僅引入了redis,這樣有了兩個容器,但隨着業務的增長,你可能還須要mysql,ssdb,rabbitmq,nginx等服務,而docker建議的就是一個容器

一個進程,那爲了能順利承載這些服務,你可能須要部署6個容器,若是你仍是按照老一套的方法一個一個的去部署,操做起來就比較亂,有沒有一種方式可

以讓docker自動幫咱們一鍵部署好這些容器呢? 就好像dockerfile那樣自動化部署,固然有了,那就是docker-compose 容器編排。

 

1. 安裝

    官網地址:https://docs.docker.com/compose/install/#install-compose  而後按照步驟一步一步來就行了,最後經過docker-compose --version 看一下便可。

[root@localhost publish]# sudo curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
[root@localhost publish]# sudo chmod +x /usr/local/bin/docker-compose
[root@localhost publish]# docker-compose --version
docker-compose version 1.22.0, build f46880fe
[root@localhost publish]#

 

2. 編寫docker-compose 

    docker-compose的全部命令都在 https://docs.docker.com/compose/compose-file/  上面找獲得,若是有興趣能夠查看一下。

version: '3.0'
services:
  webnotebook:
    container_name: webnotebook
    build: 
      context: .
      dockerfile: ./Dockerfile
    depends_on:
      - redis
    links:
      - "redis:redis.webnotebook.com"
    ports:
      - "8080:8080"
  redis:
   container_name: some-redis
   image: redis

 

   上面的配置看起來不難吧,若是不知道參數的意思,仍是那句話,查看官方文檔, 最後你可使用 docker-compose up --build 跑起來,或者使用 -d 參數

進行後臺運行。

[root@localhost publish]# docker-compose up --build
Building webnotebook
Step 1/9 : FROM microsoft/dotnet:2.2-aspnetcore-runtime
 ---> dad26d192ae6
Step 2/9 : ENV TZ Asia/Shanghai
 ---> Using cache
 ---> 72535a350c5d
Step 3/9 : LABEL author hxc@qq.com
 ---> Using cache
 ---> d4dcb4ba06aa
Step 4/9 : RUN mkdir /data
 ---> Using cache
 ---> 6bbfc1537e42
Step 5/9 : COPY ./ /data
 ---> Using cache
 ---> 5401b74ec21f
Step 6/9 : WORKDIR /data
 ---> Using cache
 ---> d93e7949b527
Step 7/9 : VOLUME /data/log
 ---> Using cache
 ---> 39c4285c6d6c
Step 8/9 : EXPOSE 8080
 ---> Using cache
 ---> d02932ddfbcc
Step 9/9 : CMD [ "dotnet","WebNotebook.dll" ]
 ---> Using cache
 ---> 0572ceea51a1
Successfully built 0572ceea51a1
Successfully tagged publish_webnotebook:latest
Starting some-redis ... done
Starting webnotebook ... done
Attaching to some-redis, webnotebook
some-redis     | 1:C 22 Feb 2019 09:11:03.160 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
some-redis     | 1:C 22 Feb 2019 09:11:03.160 # Redis version=5.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
some-redis     | 1:C 22 Feb 2019 09:11:03.160 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
some-redis     | 1:M 22 Feb 2019 09:11:03.161 * Running mode=standalone, port=6379.
some-redis     | 1:M 22 Feb 2019 09:11:03.161 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
some-redis     | 1:M 22 Feb 2019 09:11:03.161 # Server initialized
some-redis     | 1:M 22 Feb 2019 09:11:03.161 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
some-redis     | 1:M 22 Feb 2019 09:11:03.161 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
some-redis     | 1:M 22 Feb 2019 09:11:03.161 * Ready to accept connections
webnotebook    | : Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
webnotebook    |       User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
webnotebook    | Hosting environment: Production
webnotebook    | Content root path: /data
webnotebook    | Now listening on: http://[::]:8080
webnotebook    | Application started. Press Ctrl+C to shut down.

很是簡單吧,只要我有一個docker-comose文件就能夠實現一鍵部署,好了,但願本篇對你有幫助。

相關文章
相關標籤/搜索