使用docker-compose 大殺器來部署服務 - 上

我們都聽過或者用過 docker,然而使用方式卻是僅僅用手動的方式,這樣去操作 docker 還是很原始。 好吧,可能在小白的眼中噼裏啪啦的對着 term 一頓操作會很拉風,但是高手很不屑!在高手眼裏…too young, too low. 因爲高手都是自動化的,今天就稍微介紹下自動化工具,也就是大殺器 docker-compose

先從 docker 說起

我知道可能有些看到這篇文章的朋友沒有了解或者使用過 docker,那我就在這裏做一個小小的介紹,已經有過了解的朋友請直接從docker-compose部分看起.

docker 簡介

想要理解 docker 是啥,就要先說說 docker 可以解決啥
一句話來說

docker 是一種容器技術,作用是用來快速部署服務

爲什麼說 docker 是快速部署

我們做一個項目,最不想面對的不是開發,也不是調試,而是部署!!!!
比如你這個機器上的環境是 python3 你用另一個機器上卻是 python2 或者壓根就沒有 python 環境。

好了,這個時候你怎麼解決呢。 對,只要去新機器上你就要部署 python。

嗯~ 好吧, 部署 python 就 python,但是你的項目裏面還要用到 MySQL,好的沒問題, 你又要去用 pip 去安裝 python 的 mysql 模塊。 哦對了, 我記我們的項目裏面還有 redis, 兩種非對稱加密,還有三方隊列, 哦, 還有阿里雲的接口,對對對對對對哦。 亂七八糟的東西真的好多,搞完了幾個小時沒有了,遇到網絡卡了,那就更沒有譜了。

好了, 我們進化到,快速1.0 時代

我們把要安裝的東西全都放進離線安裝包裏面,再寫個 bash 腳本
對,這種事情真的有過。 部署全靠一個 bash 腳本,畢竟不用手動了麼。 可是就是苦了寫腳本的人,我就寫過一個腳本寫了好久。

於是, 我們又進化了, 快速2.0時代

我們把整個系統做成了鏡像,存在了光盤裏面,每當要架設的時候趕快用鏡像做出一個新的系統!
可能經歷過的自然會懂,還特麼要做鏡像啊,離機房遠咋辦啊!!我們做遊戲,開服快,更新更快!我們版本更新過快怎麼辦啊!!我們還要刻刻刻麼? 我們的 tornado 又更新了,我去,我們客戶端的 protobuf 也更新了,可是我們有100臺服務器啊,爲了這一點小小的東西更新麼?西八!

於是,我們再次加入光榮的進化, 快速3.0時代

我們把服務裝進了 docker 中
我們把做好的鏡像,一個命令 pull 了下來,嗯,蠻快又一個命令 docker start XXXXXX 服務起來了。哦,你說多服務?好吧那就寫個docker-compose.file吧。 嗯哼? 你說集羣部署 來來來, 有Kubernetes、Mesos,Fleet和Swarm 任君挑選,不好用不要錢。

docker 是部署的最佳輔助,即使你爛成渣渣,docker 也可以扶你上王者。

docker 安裝

 


很簡單 docker官網
屏幕快照 2017-03-05 下午7.43.29
Get docker 之後, 有圖型系統(windows 之類)的有下一步,下一步。 有 term 接口的。 有 apt-get 之類的軟件管理。
安裝非常簡單,不值得一說。

 

docker 的一些概念

鏡像

對!就和我上面說的使用光盤拷貝已經有的鏡像一樣,我們的鏡像是指一個系統的鏡像
我們的鏡像都是基於 linux 的準確來說是基於 ubuntu 的。
docker 鏡像可以理解爲,你在 win 下用ghost 拷貝出來的磁盤鏡像。不過他是 linux 版的。

性能損耗

得益於現在的 linux 內核的 namespace, 我們可以擁有各種直達內耗的容器可以用,你在 docker 中的進程其實進程就是直接的宿主機進程,這一切都在系統啓動 clone 函數的時候就決定了, 所以談不上性能損耗。

容器

容器本身就是我們最重要的概念,我們使用 docker 要做的就是容器這個東西。

簡單來說容器是一個鏡像的實例

更通俗來說容器就像你用 vm 或者 virtualbox 使用鏡像創建的一個虛擬機實例

hub

就是鏡像倉庫。

如果你寫代碼,你肯定就知道 github,我們把代碼託管到 github 之上。
如果我們部署,我肯定就要用 dockerhub, 我們把鏡像託管到 docker hub 上(當然我們也可以假設,或者是用別人假設的hub)
國內有很多三方 dockerhub 服務器, 有阿里雲,網易蜂巢,有容雲,daocloud 等等等等
至於國外那就更多了,如果非要推薦一家,那就是 amazon 了,畢竟雲服務他們家宇宙最強,沒有之一,沒有對手。

docker 簡單使用

搜索鏡像

docker search xxx
比如我要架設一個 wordpress,我直接就用
docker search wordpress

root@ubuntu:~# docker search wordpress
NAME                         DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
wordpress                    The WordPress rich content management syst...   1574      [OK]       
appcontainers/wordpress      Centos/Debian Based Customizable Wordpress...   34                   [OK]
bitnami/wordpress            Bitnami Docker Image for WordPress              30                   [OK]
centurylink/wordpress        Wordpress image with MySQL removed.             12                   [OK]
trafex/wordpress             Wordpress container with Nginx 1.10 & PHP-...   5                    [OK]
maximiliend/wordpress        A enhanced docker image of WordPress with ...   4                    [OK]
devgeniem/wordpress-server   Minimal wordpress server with nginx and ph...   3                    [OK]
scjalliance/wordpress        WordPress with GD and FreeType                  2                    [OK]
dsifford/wordpress           A WordPress docker environment that just w...   2                    [OK]
bakudankun/wordpress-ja      WordPress Japanese Edition forked from off...   1                    [OK]
ddaishin/wordpress           Wordpress日本語最新版 Xdebug OSX...                   1                    [OK]
dsteinkopf/wordpress         wordpress clone plus some php extensions        1                    [OK]
nitra/wordpress              nitra/wordpress image                           0                    [OK]
miqueladell/wordpress        Just a tailor made Wordpress.                   0                    [OK]
ikoptiev/wordpress           Official Wordpress image with max file upl...   0                    [OK]
tagplus5/wordpress           wordpress                                       0                    [OK]
rwindegger/wordpress         A wordpress php-fpm backend.                    0                    [OK]
appeine/wordpress            Container holding WordPress sources             0                    [OK]
wppier/wordpress             wordpress-php7.0-fpm-alpine                     0                    [OK]
svendocker/wordpress         wordpress + mcrypt  and recode                  0                    [OK]
indiehosters/wordpress       WordPress image for IndieHosters service        0                    [OK]
derjudge/wordpress           1:1 clone of docker-library/wordpress with...   0                    [OK]
momonga/wordpress            wordpress with mbstring, sendmail               0                    [OK]
deardooley/wordpress         Production-ready minimal Wordpress images.      0                    [OK]
bearbeer/wordpress           Wordpress with ssmtp.                           0                    [OK]
root@ubuntu:~# 

第一列就是你可以選擇使用的鏡像,你當然可以自己製作鏡像,而且很容易,但是如果我們入門的話就直接用別人做好的吧。

下載鏡像

我直接用第一個吧
git pull wordpress
這個是在下載鏡像的過程中

root@ubuntu:~# docker pull wordpress
Using default tag: latest
latest: Pulling from library/wordpress
693502eb7dfb: Pull complete 
16328c296404: Pull complete 
8b3c97761df6: Pull complete 
5e1d4f4f29eb: Pull complete 
530750fc5019: Extracting [==================================================>] 1.252 kB/1.252 kB
39e9c6c72db7: Download complete 
de476ce7ac87: Download complete 
4ad13cbbc7d8: Download complete 
74c28aa07dc7: Download complete 
a07a242e36fb: Download complete 
3d491d166e88: Download complete 
cb6c232330f0: Download complete 
25a48aec9dc7: Download complete 
836344dc17d7: Download complete 
f5cafd105c82: Download complete 
fef842449a96: Download complete 
9b13cded57f6: Download complete 
0733368296e4: Download complete 

下載完成

root@ubuntu:~# docker pull wordpress
Using default tag: latest
latest: Pulling from library/wordpress
693502eb7dfb: Pull complete 
16328c296404: Pull complete 
8b3c97761df6: Pull complete 
5e1d4f4f29eb: Pull complete 
530750fc5019: Pull complete 
39e9c6c72db7: Pull complete 
de476ce7ac87: Pull complete 
4ad13cbbc7d8: Pull complete 
74c28aa07dc7: Pull complete 
a07a242e36fb: Pull complete 
3d491d166e88: Pull complete 
cb6c232330f0: Pull complete 
25a48aec9dc7: Pull complete 
836344dc17d7: Pull complete 
f5cafd105c82: Pull complete 
fef842449a96: Pull complete 
9b13cded57f6: Pull complete 
0733368296e4: Pull complete 
Digest: sha256:498509cc3778374f65037f8dae67bb660d4fe650e8ac2129135224d5d2d81726
Status: Downloaded newer image for wordpress:latest

helloworld

程序員的老慣例了

root@ubuntu:~# docker run wordpress echo "hello world"
hello world 

這句其實就相當於你的鏡像

做到 helloworld 了你就算是入門了。哈哈哈。

推薦一個寫很有層次感的入門docker入門教程

我常用的 docker 命令

你可以使用幫助看一個命令的大概

docker   # docker 命令幫助

Commands:
    attach    Attach to a running container                 # 當前 shell 下 attach 連接指定運行鏡像
    build     Build an image from a Dockerfile              # 通過 Dockerfile 定製鏡像
    commit    Create a new image from a container's changes # 提交當前容器爲新的鏡像
    cp        Copy files/folders from the containers filesystem to the host path
              # 從容器中拷貝指定文件或者目錄到宿主機中
    create    Create a new container                        # 創建一個新的容器,同 run,但不啓動容器
    diff      Inspect changes on a container's filesystem   # 查看 docker 容器變化
    events    Get real time events from the server          # 從 docker 服務獲取容器實時事件
    exec      Run a command in an existing container        # 在已存在的容器上運行命令
    export    Stream the contents of a container as a tar archive   
              # 導出容器的內容流作爲一個 tar 歸檔文件[對應 import ]
    history   Show the history of an image                  # 展示一個鏡像形成歷史
    images    List images                                   # 列出系統當前鏡像
    import    Create a new filesystem image from the contents of a tarball  
              # 從tar包中的內容創建一個新的文件系統映像[對應 export]
    info      Display system-wide information               # 顯示系統相關信息
    inspect   Return low-level information on a container   # 查看容器詳細信息
    kill      Kill a running container                      # kill 指定 docker 容器
    load      Load an image from a tar archive              # 從一個 tar 包中加載一個鏡像[對應 save]
    login     Register or Login to the docker registry server   
              # 註冊或者登陸一個 docker 源服務器
    logout    Log out from a Docker registry server         # 從當前 Docker registry 退出
    logs      Fetch the logs of a container                 # 輸出當前容器日誌信息
    port      Lookup the public-facing port which is NAT-ed to PRIVATE_PORT
              # 查看映射端口對應的容器內部源端口
    pause     Pause all processes within a container        # 暫停容器
    ps        List containers                               # 列出容器列表
    pull      Pull an image or a repository from the docker registry server
              # 從docker鏡像源服務器拉取指定鏡像或者庫鏡像
    push      Push an image or a repository to the docker registry server
              # 推送指定鏡像或者庫鏡像至docker源服務器
    restart   Restart a running container                   # 重啓運行的容器
    rm        Remove one or more containers                 # 移除一個或者多個容器
    rmi       Remove one or more images                 
              # 移除一個或多個鏡像[無容器使用該鏡像纔可刪除,否則需刪除相關容器纔可繼續或 -f 強制刪除]
    run       Run a command in a new container
              # 創建一個新的容器並運行一個命令
    save      Save an image to a tar archive                # 保存一個鏡像爲一個 tar 包[對應 load]
    search    Search for an image on the Docker Hub         # 在 docker hub 中搜索鏡像
    start     Start a stopped containers                    # 啓動容器
    stop      Stop a running containers                     # 停止容器
    tag       Tag an image into a repository                # 給源中鏡像打標籤
    top       Lookup the running processes of a container   # 查看容器中運行的進程信息
    unpause   Unpause a paused container                    # 取消暫停容器
    version   Show the docker version information           # 查看 docker 版本號
    wait      Block until a container stops, then print its exit code   
              # 截取容器停止時的退出狀態值
Run 'docker COMMAND --help' for more information on a command.

登錄

登錄你自己的 dockerhub 賬戶,要去註冊哦
來docker hub註冊啊
docker login

查看容器

查看你已經下載好的鏡像
docker images

查找鏡像

docker search XX

下載鏡像

docker pull xx

刪除鏡像

docker rmi xx

開始

docker run 你的鏡像

看日誌

docker logs 你的容器

停止一個容器示例

docker stop 你的容器

查看容器狀態

docker stats 你的容器

格式

基本上都是這個格式 ,根據上面寫好的註釋,很容易去使用

更快更好更強

  • 使用 dockerfile
  • 使用 crontab
  • 使用 supervisr

略, 這個要扯起來就太長了

docker-compose 簡介

 


一句話
docker-compose 是用來做docker 的多容器控制

 

docker-compose 是什麼

docker-compose 是一個用來把 docker 自動化的東西。
有了 docker-compose 你可以把所有繁複的 docker 操作全都一條命令,自動化的完成。

爲什麼要用 docker-compose,他解決了什麼

用通俗的語言來說,我們平時操作 docker 還是很原始的一系列動作,你手動使用 docker 的動作可以拆分成

  1. 找到一個系統鏡像 // docker search
  2. 安裝好 vm 或者 virtual box // apt-get install docker
  3. 在 vm 中安裝鏡像 // docker run -d -it 你的鏡像
  4. 略..

這是最小的動作, 如果你要映射硬盤,設置nat網絡或者橋接網絡,等等…你就要做更多的 docker 操作, 這顯然是非常沒有效率的。

但是我們寫在 docker-compose.file 裏面就很好了。 你只需要寫好後 只運行一句
docker-compose up -d
一切都是那麼的簡單

那麼哪裏可以買到呢?

你要你能上網,到處都可以得到他。
我自己的機器上有 python&pip 的環境,所以我的安裝非常簡單

 


先確定你是不是安裝了 docker
沒有安裝請看上面的文章

 

我的環境是
linux-ubuntu:python2:pip
所以我的安裝
pip install docker-compose
如此簡單

從一個小例開始

root@ubuntu:~/test# cat docker-compose.yml 
version: '2'
services:
  mariadb:
    image: 'bitnami/mariadb:latest'
    environment:
      - ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - /path/to/mariadb-persistence:/bitnami/mariadb

root@ubuntu:~/test# docker-compose up
Creating network "test_default" with the default driver
Creating test_mariadb_1
Attaching to test_mariadb_1
mariadb_1  | 
mariadb_1  | Welcome to the Bitnami mariadb container
mariadb_1  | Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-mariadb
mariadb_1  | Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-mariadb/issues
mariadb_1  | Send us your feedback at [email protected]
mariadb_1  | 
mariadb_1  | nami    INFO  Initializing mariadb
mariadb_1  | mariadb INFO  ==> Creating 'root' user with unrestricted access...
mariadb_1  | mariadb INFO  ==> Flushing privileges...
mariadb_1  | mariadb INFO  ==> Enabling remote connections...
mariadb_1  | mariadb INFO 
mariadb_1  | mariadb INFO  ########################################################################
mariadb_1  | mariadb INFO   Installation parameters for mariadb:
mariadb_1  | mariadb INFO     Root Password: Not set during installation
mariadb_1  | mariadb INFO   (Passwords are not shown for security reasons)
mariadb_1  | mariadb INFO  ########################################################################
mariadb_1  | mariadb INFO 
mariadb_1  | nami    INFO  mariadb successfully initialized
mariadb_1  | INFO  ==> Starting mariadb...
mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: Highest supported file format is Barracuda.
mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: 128 rollback segment(s) are active.
mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: Waiting for purge to start
mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.34-79.1 started; log sequence number 1616829
mariadb_1  | 2017-03-05 15:01:27 139902956046080 [Note] InnoDB: Dumping buffer pool(s) not yet started

先安裝吧

如果你和我的環境相同,請直接看我的 docker-compose 安裝

如果是別的話,別擔心,這裏有
安裝指南

helloworld

root@ubuntu:~/test# cat docker-compose.yml 
version: '2'
services:
  mariadb:
    image: 'bitnami/mariadb:latest'
    environment:
      - ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - /path/to/mariadb-persistence:/bitnami/mariadb
    command: echo "hello world"
root@ubuntu:~/test# 
root@ubuntu:~/test# 
root@ubuntu:~/test# docker-compose up      
Starting test_mariadb_1
Attaching to test_mariadb_1
mariadb_1  | 
mariadb_1  | Welcome to the Bitnami mariadb container
mariadb_1  | Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-mariadb
mariadb_1  | Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-mariadb/issues
mariadb_1  | Send us your feedback at [email protected]
mariadb_1  | 
mariadb_1  | hello world
test_mariadb_1 exited with code 0

服務更新

軟升級

$ docker-compose stop wordpress
停止容器運行

$ docker-compose rm wordpress
刪除老舊的容器
更新你的 image

$ docker-compose start wordpress
啓動新容器

還比如

你的 nginx 更新了配置文件之後

docker-compose restart nginx

硬升級

docker-compose stop

升級你的程序

你要重新
docker-compose up

從日誌得到需要的信息

直接使用 logs

docker-compose logs nginx
歐 shit 直接給我屏幕刷爆了

使用類似linux tail 命令

我們的 tial 命令一般是什麼樣的呢
tail -f xx.file

我們的docker-compose log 卻是這樣

root@ubuntu:~# docker-compose logs -f --tail 10 nginx
Attaching to root_nginx_1
nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-admin/ HTTP/1.1" 302 0 "http://www.yunlan.name/wp-admin/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-login.php?action=lostpassword HTTP/1.1" 200 1201 "http://www.yunlan.name/wp-login.php?action=lostpassword" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-login.php?action=lostpassword HTTP/1.1" 200 1201 "-" "Mozilla"
nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-login.php?redirect_to=http%3A%2F%2Fwww.yunlan.name%2Fwp-admin%2F&reauth=1 HTTP/1.1" 200 1265 "http://www.yunlan.name/wp-admin/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:19 +0000] "GET /wp-login.php?redirect_to=http%3A%2F%2Fwww.yunlan.name%2Fwp-admin%2F&reauth=1 HTTP/1.1" 200 1265 "-" "Mozilla"
nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:57:52 +0000] "GET /robots.txt HTTP/1.1" 200 134 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:03 +0000] "GET / HTTP/1.1" 499 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:03 +0000] "GET / HTTP/1.1" 200 3844 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:03 +0000] "GET /wp-content/plugins/code-prettify/prettify/run_prettify.js?ver=1.3.4 HTTP/1.1" 200 7600 "http://www.yunlan.name/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:04 +0000] "GET /wp-content/plugins/code-prettify/prettify/prettify.css HTTP/1.1" 200 722 "http://www.yunlan.name/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"


最近的10條開始

docker-compose 常用命令


Commands:
  build              Build or rebuild services
  bundle             Generate a Docker bundle from the Compose file
  config             Validate and view the compose file
  create             Create services
  down               Stop and remove containers, networks, images, and volumes
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pull service images
  push               Push service images
  restart            Restart services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            Show the Docker-Compose version information

解釋一下

build 構建或重建服務
help 命令幫助
kill 殺掉容器
logs 顯示容器的輸出內容
port 打印綁定的開放端口
ps 顯示容器
pull 拉取服務鏡像
restart 重啓服務
rm 刪除停止的容器
run 運行一個一次性命令
scale 設置服務的容器數目
start 開啓服務
stop 停止服務
up 創建並啓動容器

docker-compose 如何配置

先看看我自己寫的一個 docker-compose.yml

version: '2'
services:
    nginx:
            image: bitnami/nginx:latest
            ports:
                - '80:80'
                - '1443:443'
            volumes:
                - /root/wp_yunlan/nginx/:/bitnami/nginx/
    mariadb:
            image: bitnami/mariadb:latest
            volumes:
                - /root/wp_yunlan/mariadb:/bitnami/mariadb
    wordpress:
            image: bitnami/wordpress:latest
            depends_on:
                - mariadb
                - nginx
            environment:
                - WORDPRESS_USERNAME=neptunemoon    #這個賬戶你是自己設定的
                - WORDPRESS_PASSWORD=123123         #這個密碼是你自己設定的
            ports:
                - '8080:80'
                - '8081:443'
            volumes:
                - /root/wp_yunlan/wordpress:/bitnami/wordpress
                - /root/wp_yunlan/apache:/bitnami/apache
                - /root/wp_yunlan/php:/bitnami/php

nginx 和 mariadb,wordpress 是要啓動的三個服務

順序不是重要的,我們看見wordpress中有個 depends_on: 的屬性

depends_on: 依賴

代表wordpress 依賴於

- mariadb
- nginx

兩個服務, 所以他們兩個會先啓動

image: 鏡像

就是你的 docker 鏡像
我們用
docker search mariadb
找到我們需要的鏡像

root@ubuntu:~/test# docker search mariadb
NAME                         DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mariadb                      MariaDB is a community-developed fork of M...   1192      [OK]       
paintedfox/mariadb           A docker image for running MariaDB 5.5, a ...   29                   [OK]
bitnami/mariadb              Bitnami MariaDB Docker Image                    29                   [OK]
million12/mariadb            MariaDB 10 on CentOS-7 with UTF8 defaults       12                   [OK]
toughiq/mariadb-cluster      Dockerized Automated MariaDB Galera Cluste...   9                    [OK]
webhippie/mariadb            Docker images for mariadb                       6                    [OK]
panubo/mariadb-galera        MariaDB Galera Cluster                          6                    [OK]
kakilangit/mariadb           Docker for MariaDB with OQGraph & TokuDB E...   5                    [OK]
maxexcloo/mariadb            Service container with MariaDB installed a...   4                    [OK]
tcaxias/mariadb              MariaDB containers                              1                    [OK]
desertbit/mariadb            This is an extended docker image of the of...   1                    [OK]
russmckendrick/mariadb       A MariaDB image                                 1                    [OK]
drupaldocker/mariadb         MariaDB for Drupal                              1                    [OK]
jpco/mariadb                 Mariadb, so I can have it on my raspberry       1                    [OK]
clearlinux/mariadb           MariaDB Server                                  1                    [OK]
danielsreichenbach/mariadb   Minimal MariaDB container to be used as co...   0                    [OK]
lucidfrontier45/mariadb      Mariadb with some customizable properties       0                    [OK]
codete/mariadb               MariaDB docker image used at Codete.            0                    [OK]
dogstudio/mariadb            MariaDB Container for Dogs                      0                    [OK]
babim/mariadb                Mariadb Server on Alpine or Debian. Check ...   0                    [OK]
objectstyle/mariadb          ObjectStyle MariaDB Docker Image                0                    [OK]
oriaks/mariadb               MariaDB                                         0                    [OK]
yannickvh/mariadb            Custom build of MariaDB based on the offic...   0                    [OK]
gymnae/mariadb               Alpine based simple mariadb                     0                    [OK]
nimmis/mariadb               MariaDB multiple versions based on nimmis/...   0                    [OK]
root@ubuntu:~/test# 

好了,就是bitnami/mariadb

如果你看見有的麼有 images ,而是一個 build, 那個說明這個不是用鏡像的,而是使用 dockerfile 去構建容器。
如果要說 dockerfile 又要花很久了

想了解 dockerfile 可以看這裏
編寫Dockerfile

environment 環境變量

這個是在好理解不過的了。
不過這和我們程序語言設計層面的還是不一樣的,這個是容器層面的環境變量。
如果我們寫程序做一些邏輯判斷的時候,肯定會使用
比如我們判斷現在的編譯器,我們會使用
#if __GNUC__ 或者 #if _MSC_VER
相應的,我們的容器裏面肯定也有這樣的邏輯,我們經常使用環境變量來傳值,或者定義一個行爲。寫過程序的人都懂。

ports 端口映射

映射本機還有鏡像的端口。這個沒有什麼好說的。

volumes 文件映射

有兩種格式,
可以對應 docker 操作中的 -v my/path/:/docker/path
還可以使用單方面的 -v /path
這樣的話 就相當於 一個匿名映射, 其實還是在本機有對應目錄的。

使用docker inspect -f {{.Volumes}} /path 可以看到詳細信息

相對這個瞭解更多的 深入理解Docker Volume

docker-compose 需要注意的

我根據我自己的體驗,給出幾點需要注意的

  1. 不要把 docker 當做數據容器來使用,數據一定要用 volumes 放在容器外面
  2. 不要把 docker-compose 文件暴露給別人, 因爲上面有你的服務器信息
  3. 多用 docker-compose 的命令去操作, 不要用 docker 手動命令&docker-compose 去同時操作
  4. 寫一個腳本類的東西,自動備份docker 映射出來的數據。
  5. 不要把所有服務都放在一個 docker 容器裏面

針對需求開始部署了

設定一個需求

我假定現在我們的需求是做一個博客系統

我們的第一印象肯定是 wordpress, 沒有比這個更專業的了, 當然還有很多,我們使用 django 吧

用過 django 的肯定會知道, django 一開始是要構造工程的。
還有數據之類的

我們擬訂一個過程

  1. python 環境搭建
  2. django 環境搭建
  3. docker-compose.yml 寫作
  4. django 構建工程
  5. django 數據庫設定
  6. 開始運行
  7. 數據庫同步

簡單的單機部署

python 環境搭建

Dockerfile

ENV PYTHONUNBUFFERED 1
RUN mkdir /root/testdjango/code    #都寫上絕對路徑, 注意不要跟我一樣。
WORKDIR /root/testdjango/code
ADD requirements.txt /root/testdjango/code/
RUN pip install -r requirements.txt
ADD . /root/testdjango/code/

python 的pip 有一個requirements.txt 文件來專門放依賴環境的

django 環境搭建

requirements.txt

Django
psycopg2

docker-compose.yml 寫作

db:
  image: postgres
web:
  build: .
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db

django 構建工程

docker-compose run web django-admin.py startproject docker_composeexample .

django 數據庫設定

我們做了 volumes, django 的東西在本地有映射。
做過 django 的人都知道 ,我們的設定都在 settings.py 中

root@ubuntu:~/testdjango/docker_composeexample# cat settings.py 
"""
Django settings for docker_composeexample project.

Generated by 'django-admin startproject' using Django 1.10.6.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3*@nbl2pu$hdmpe-hy&iko_cr_-$%9g=nu2=3x_^g(vy2463d6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'docker_composeexample.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'docker_composeexample.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
root@ubuntu:~/testdjango/docker_composeexample# 

我們只設置 數據庫

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

開始運行

docker-compose up

數據庫同步

docker-compose run web python manage.py syncdb

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章