本文主要參考Docker Compose官方文檔研究其安裝、使用。

Overview

Docker Compose是定義和運行多容器的Docker應用的工具。通過Compose,您使用一個Compose文件配置您的應用的服務,然後使用一個簡單的命令,您就可以創建、啓動您配置文件中的所有服務。

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a Compose file to configure your application’s services. Then, using a single command, you create and start all the services from your configuration.

使用Compose只需簡單的三步: 1. 使用Dockerfile定義app的環境,使之能在任意地方重新生成; 2. 在docker-compose.yml中構成您app的服務,使其能在獨立的環境中運行在一起; 3. 運行docker-compose up命令,Compose將會啓動並運行您的整個app;

Using Compose is basically a three-step process.

  1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
  2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
  3. Lastly, run docker-compose up and Compose will start and run your entire app.

docker-compose.yml文件內容構成格式像如下這種

version: '2'
services:
  web:
    build: .
    ports:
    - "5000:5000"
    volumes:
    - .:/code
    - logvolume01:/var/log
    links:
    - redis
  redis:
    image: redis
volumes:

Compose文件的具體 指令,參見Compose file reference

Compose有管理應用整個生命週期的命令: * Start, stop and rebuild services * View the status of running services * Stream the log output of running services * Run a one-off command on a service

Features

Installation

不管是Debian還是CentOS系統,Docker對系統的要求是64-bit,同時內核版本至少得是3.10

在安裝Docker Compoase之前需先安裝Docker Engine,請確保有sutoroot權限。

Docker Engine Installation

Debian 以Debian Jessie爲例

# 移除舊的Docker
sudo apt-get purge "lxc-docker*"
sudo apt-get purge "docker.io*"

# 更新安裝包信息,安裝CA證書
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates

# 安裝GPG key
sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D

# 添加Docker倉庫
sudo tee /etc/apt/sources.list.d/docker.list <<-'EOF'
deb https://apt.dockerproject.org/repo debian-jessie main
EOF

# 更新安裝包索引
sudo apt-get update

# 驗證apt可以從Docker倉庫拉取信息
apt-cache policy docker-engine

# 安裝Docker
sudo apt-get install docker-engine

# 啓動Docker服務
sudo service docker start
或
sudo systemctl status docker
sudo systemctl start docker

# 添加用戶到Docker用戶組中
sudo groupadd docker
sudo gpasswd -a ${USER} docker
sudo systemctl restart docker

# 更新服務
sudo apt-get upgrade docker-engine

CentOS以CentOS 7爲例

# 更新系統,確保最新
sudo yum update

# 添加Docker倉庫
sudo tee /etc/yum.repos.d/docker.repo <<-'EOF'
[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/7/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg
EOF

# 安裝Docker engine
sudo yum install docker-engine

# 啓動Docker服務
sudo service docker start
或
sudo systemctl start docker
sudo systemctl enable docker

# 添加用戶到Docker用戶組中
sudo groupadd docker
sudo gpasswd -a ${USER} docker
sudo systemctl restart docker

Docker Compose Installation

此處之介紹使用Curl命令安裝docker-compose,如果要使用pip命令安裝,可參考官方文檔Install Docker Compose

Compose在GitHub的releae頁面選擇需要的版本

注意 直接執行

curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

會出現報錯,提示權限不夠 > bash: /usr/local/bin/docker-compose: Permission denied

可通過sudo -i先切換到root用戶再執行相關命令

# 切換到root用戶
sudo -i

# 下載compose
curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

# 添加執行權限
chmod +x /usr/local/bin/docker-compose

操作過程

# 切換到root用戶
lemp@lempstacker:~$ sudo -i

# 下載compose
root@lempstacker:~# curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   600    0   600    0     0    204      0 --:--:--  0:00:02 --:--:--   204
100 7783k  100 7783k    0     0   306k      0  0:00:25  0:00:25 --:--:--  380k

# 查看權限
root@lempstacker:~# ls -lh /usr/local/bin/docker-compose
-rw-r--r-- 1 root staff 7.7M Aug 28 10:54 /usr/local/bin/docker-compose

# 添加執行權限
root@lempstacker:~# chmod +x /usr/local/bin/docker-compose

#再次查看權限
root@lempstacker:~# ls -lh /usr/local/bin/docker-compose
-rwxr-xr-x 1 root staff 7.7M Aug 28 10:54 /usr/local/bin/docker-compose
root@lempstacker:~#

查看版本信息

# root用戶
root@lempstacker:~# docker-compose --version
docker-compose version 1.8.0, build f3628c7
root@lempstacker:~# exit
logout

# 普通用戶
lemp@lempstacker:~$ docker-compose --version
docker-compose version 1.8.0, build f3628c7
lemp@lempstacker:~$

Remove

如果需要移除docker-compose,只需將其可執行文件刪除即可

sudo rm /usr/local/bin/docker-compose

QuickStart

參照官方文檔Quickstart: Docker Compose and WordPress進行實驗。需要用到的Docker Image有mariadbwordpress

lemp@lempstacker:~$ docker images | awk '$1~/mariadb|wordpress/{printf("%s:%s\n",$1,$2)}'
wordpress:latest
mariadb:latest
lemp@lempstacker:~$

Define the project

在家目錄下創建Docker目錄

# 創建Docker目錄
mkdir -pv ~/Docker

# 創建docker-compose.yml
touch docker-compose.yml

參考二者在Docker Registry中的說明 * WordPress * MariaDB

設置相關環境變量

There are two versions of the Compose file format:

  • Version 1, the legacy format. This is specified by omitting a version key at the root of the YAML.
  • Version 2, the recommended format. This is specified with a version: '2' entry at the root of the YAML.

Compose yaml File

以下是文件docker-compose.yml的具體內容

version: '2'
services:
  database:
    image: mariadb:latest
    volumes:
      - "./datadir:/var/lib/mysql"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: rootpw_lempstacker
      MYSQL_DATABASE: wordpress
      MYSQL_USER: user_wordpress
      MYSQL_PASSWORD: pw_lempstacker
    #   MYSQL_ALLOW_EMPTY_PASSWORD
    #   MYSQL_RANDOM_ROOT_PASSWORD
    #   MYSQL_ONETIME_PASSWORD

  wordpress:
    depends_on:
      - database
    image: wordpress:latest
    links:
      - database
    ports:
      - "8000:80"
    restart: always
    environment:
    # 默認是鏈接的mysql容器中的IP和端口
      WORDPRESS_DB_HOST: database:3306
    # 默認是root
      WORDPRESS_DB_USER: user_wordpress
    # 默認是鏈接的mysql容器中的環境變量MYSQL_ROOT_PASSWORD的值
      WORDPRESS_DB_PASSWORD: pw_lempstacker
    # 默認是 wordpress
      WORDPRESS_DB_NAME: wordpress
    # 默認是 ""
    #   WORDPRESS_TABLE_PREFIX

本機指定的映射端口是8000,可通過命令

ss -tnl

查看該端口是否被佔用

Build the project

在文件docker-compose.yml所在目錄(此處爲~/Docker)中執行如下命令

docker-compose up -d

操作過程

lemp@lempstacker:~$ cd Docker/
lemp@lempstacker:~/Docker$ docker-compose up -d
Creating network "docker_default" with the default driver
Creating docker_database_1
Creating docker_wordpress_1
lemp@lempstacker:~/Docker$

在瀏覽器中輸入

http://localhost:8000

會自動跳轉到

http://localhost:8000/wp-admin/install.php`

是WordPress的安裝界面,可配置用戶名、密碼等信息。

如果/etc/hosts文件中已經設置了

127.0.0.1   localhost

也可在瀏覽器中輸入

http://http://127.0.0.1/:8000

使用curl命令抓取HTTP Header信息

lemp@lempstacker:~$ curl -I http://127.0.0.1:8000
HTTP/1.1 302 Found
Date: Sun, 28 Aug 2016 04:39:56 GMT
Server: Apache/2.4.10 (Debian)
X-Powered-By: PHP/5.6.25
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Location: http://127.0.0.1:8000/wp-admin/install.php
Content-Type: text/html; charset=UTF-8

lemp@lempstacker:~$

依次出現如下界面

再看目錄~/Docker中的目錄結構

lemp@lempstacker:~/Docker$ pwd
/home/lemp/Docker
lemp@lempstacker:~/Docker$ ls -lh
total 8.0K
drwxr-xr-x 5  999 docker 4.0K Aug 28 12:32 datadir
-rw-r--r-- 1 lemp lemp    950 Aug 28 12:29 docker-compose.yml
lemp@lempstacker:~/Docker$ ls -lh datadir/
total 173M
-rw-rw---- 1 999 docker  16K Aug 28 12:32 aria_log.00000001
-rw-rw---- 1 999 docker   52 Aug 28 12:32 aria_log_control
-rw-rw---- 1 999 docker  76M Aug 28 12:48 ibdata1
-rw-rw---- 1 999 docker  48M Aug 28 12:48 ib_logfile0
-rw-rw---- 1 999 docker  48M Aug 28 12:32 ib_logfile1
-rw-rw---- 1 999 docker    0 Aug 28 12:32 multi-master.info
drwx------ 2 999 docker 4.0K Aug 28 12:32 mysql
drwx------ 2 999 docker 4.0K Aug 28 12:32 performance_schema
-rw-rw---- 1 999 docker  24K Aug 28 12:32 tc.log
drwx------ 2 999 docker 4.0K Aug 28 12:41 wordpress
lemp@lempstacker:~/Docker$

Relevant Command

執行

docker-compose --help

可查看其支持的命令

command explanation
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 Pulls 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
unpause Unpause services
up Create and start containers
version Show the Docker-Compose version information

docker-compose ps

列出運行的容器信息

lemp@lempstacker:~/Docker$ docker-compose ps
       Name                     Command               State          Ports         
----------------------------------------------------------------------------------
docker_database_1    docker-entrypoint.sh mysqld      Up      3306/tcp             
docker_wordpress_1   /entrypoint.sh apache2-for ...   Up      0.0.0.0:8000->80/tcp
lemp@lempstacker:~/Docker$

docker-compose config

確認並查看compose文件

lemp@lempstacker:~/Docker$ docker-compose config
networks: {}
services:
  database:
    environment:
      MYSQL_DATABASE: wordpress
      MYSQL_PASSWORD: pw_lempstacker
      MYSQL_ROOT_PASSWORD: rootpw_lempstacker
      MYSQL_USER: user_wordpress
    image: mariadb:latest
    restart: always
    volumes:
    - /home/lemp/Docker/datadir:/var/lib/mysql:rw
  wordpress:
    depends_on:
    - database
    environment:
      WORDPRESS_DB_HOST: database:3306
      WORDPRESS_DB_NAME: wordpress
      WORDPRESS_DB_PASSWORD: pw_lempstacker
      WORDPRESS_DB_USER: user_wordpress
    image: wordpress:latest
    links:
    - database
    ports:
    - 8000:80
    restart: always
version: '2.0'
volumes: {}

lemp@lempstacker:~/Docker$

docker-compose run

運行一次性(one-off)命令

此處查看環境變量

# database env
lemp@lempstacker:~/Docker$ docker-compose run database env
MARIADB_MAJOR=10.1
HOSTNAME=f39511df9a07
TERM=xterm
MYSQL_DATABASE=wordpress
MYSQL_PASSWORD=pw_lempstacker
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
SHLVL=0
HOME=/root
GOSU_VERSION=1.7
MYSQL_USER=user_wordpress
MARIADB_VERSION=10.1.16+maria-1~jessie
MYSQL_ROOT_PASSWORD=rootpw_lempstacker

# wordpress env
lemp@lempstacker:~/Docker$ docker-compose run wordpress env
HOSTNAME=6ec090244335
TERM=xterm
PHP_INI_DIR=/usr/local/etc/php
PHP_FILENAME=php-5.6.25.tar.xz
WORDPRESS_DB_PASSWORD=pw_lempstacker
PHPIZE_DEPS=autoconf 		file 		g++ 		gcc 		libc-dev 		make 		pkg-config 		re2c
WORDPRESS_DB_HOST=database:3306
WORDPRESS_VERSION=4.6
APACHE_ENVVARS=/etc/apache2/envvars
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
GPG_KEYS=0BD78B5F97500D450838F95DFE857D9A90D90EC1 6E4F6AB321FDC07F2C332E3AC2BF0BC433CFC8B3
PWD=/var/www/html
WORDPRESS_DB_USER=user_wordpress
SHLVL=0
HOME=/root
PHP_SHA256=7535cd6e20040ccec4594cc386c6f15c3f2c88f24163294a31068cf7dfe7f644
WORDPRESS_SHA1=830962689f350e43cd1a069f3a4f68a44c0339c8
APACHE_CONFDIR=/etc/apache2
PHP_EXTRA_BUILD_DEPS=apache2-dev
WORDPRESS_DB_NAME=wordpress
PHP_VERSION=5.6.25
PHP_EXTRA_CONFIGURE_ARGS=--with-apxs2
lemp@lempstacker:~/Docker$

docker-compose stop

停止服務

lemp@lempstacker:~/Docker$ docker-compose stop
Stopping docker_wordpress_1 ... done
Stopping docker_database_1 ... done
lemp@lempstacker:~/Docker$

docker-compose start

啓動服務

lemp@lempstacker:~/Docker$ docker-compose start
Starting database ... done
Starting wordpress ... done
lemp@lempstacker:~/Docker$

docker-compose down

停止並移除容器(containers)、網路(networks)、鏡像(images)和卷(volumes)

lemp@lempstacker:~/Docker$ docker-compose down
Stopping docker_wordpress_run_1 ... done
Stopping docker_database_run_1 ... done
Stopping docker_wordpress_1 ... done
Stopping docker_database_1 ... done
Removing docker_wordpress_run_1 ... done
Removing docker_database_run_1 ... done
Removing docker_wordpress_1 ... done
Removing docker_database_1 ... done
Removing network docker_default
lemp@lempstacker:~/Docker$

docker-compose rm

移除已經停止的容器

lemp@lempstacker:~/Docker$ docker-compose up -d
Creating network "docker_default" with the default driver
Creating docker_database_1
Creating docker_wordpress_1
lemp@lempstacker:~/Docker$ docker-compose stop
Stopping docker_wordpress_1 ... done
Stopping docker_database_1 ... done
lemp@lempstacker:~/Docker$ docker-compose rm -fa
WARNING: --all flag is obsolete. This is now the default behavior of `docker-compose rm`
Going to remove docker_wordpress_1, docker_database_1
Removing docker_wordpress_1 ... done
Removing docker_database_1 ... done
lemp@lempstacker:~/Docker$ docker-compose down
Removing network docker_default
lemp@lempstacker:~/Docker$

Reference

Change Logs

  • 2016.08.28 13:20 Sun Asia/Shanghai
    • 初稿完成

  • Note Time: 2016.08.28 13:20 Sun
  • Note Location: Asia/Shanghai
  • Writer: lempstacker