Docker Compose介绍

Docker Compose是Docker编排服务的最后一块,前面提到的Machine可以让用户在其它平台快速安装Docker,Swarm可以让Docker容器在集群中高效运转,而Compose可以让用户在集群中部署分布式应用



安装Docker Compose的三种方法:


官方文档:https://docs.docker.com/compose/install/#install-compose


1、直接下载编译好的二进制文件,即可使用,命令如下:

sudo curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose

卸载:

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



2、pip安装

sudo pip install docker-compose

卸载:

pip uninstall docker-compose


3、直接运行在docker容器中,这种方式适合云计算场景

$ sudo curl -L --fail https://github.com/docker/compose/releases/download/1.21.2/run.sh -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose


Compose选项

-f, --file FILE:指定使用的Compose文件,默认为docker-compose.yml,可以多次指定
-p, --project-name NAME:指定项目名称,默认将使用所在目录名称作为项目名
--x-networking:使用docker的可拔插网络后端特性,需要1.9及以上版本
--x-network-driver DRIVER:指定网络后端的驱动,默认为bridge,需要1.9及以上版本
--verbose:输出更多调试信息
-v, --version打印版本并退出


Compose命令


build:构建项目中的服务容器

Usage: build [options] [--build-arg key=val...] [SERVICE...]

Options:
    --compress              Compress the build context using gzip. 
    --force-rm              Always remove intermediate containers.    删除构建过程中的临时容器
    --no-cache              Do not use cache when building the image.   构建镜像过程中不使用缓存
    --pull                  Always attempt to pull a newer version of the image. 始终尝试通过拉取操作来获取更新版本的镜像
    -m, --memory MEM        Sets memory limit for the build container.  
    --build-arg key=val     Set build-time variables for services.

 构建项目中的服务容器,服务容器一旦构建后,将会带上一个标记名,例如对于web项目中的一个db容器,可能是web_db。可以随时在项目目录下运行docker-compose build来重新构建服务


config:验证和查看compose文件,

Usage: config [options]

Options:
    --resolve-image-digests  Pin image tags to digests.
    -q, --quiet              Only validate the configuration, don't print
                             anything.
    --services               Print the service names, one per line.
    --volumes                Print the volume names, one per line.

-q, --quiet:只验证不输出,当配置正确时,不输出任何信息,当配置错误时,输出错误信息

--services:打印服务名,一行一个

例如:

[root@OPS01-LINTEST02 composetest]# docker-compose config 
services:
  redis:
    image: redis:alpine
  web:
    build:
      context: /opt/composetest
    ports:
    - 5000:5000/tcp
    volumes:
    - /opt/composetest:/code:rw
version: '3.0'

[root@OPS01-LINTEST02 composetest]# docker-compose config -q

[root@OPS01-LINTEST02 composetest]# docker-compose config --services
web
redis



create:为服务创建容器,只是单纯的create,还需要使用start启动compose

Creates containers for a service.
This command is deprecated. Use the `up` command with `--no-start` instead.

Usage: create [options] [SERVICE...]

Options:
    --force-recreate       Recreate containers even if their configuration and
                           image haven't changed. Incompatible with --no-recreate.
    --no-recreate          If containers already exist, don't recreate them.
                           Incompatible with --force-recreate.
    --no-build             Don't build an image, even if it's missing.
    --build                Build images before creating containers.



down停止和删除容器、网络、卷、镜像,这些内容是通过docker-compose up命令创建的.  默认值删除 容器 网络,可以通过指定 rmi volumes参数删除镜像和卷

Usage: down [options]

Options:
    --rmi type              Remove images. Type must be one of:
                              'all': Remove all images used by any service.
                              'local': Remove only images that don't have a
                              custom tag set by the `image` field.
    -v, --volumes           Remove named volumes declared in the `volumes`
                            section of the Compose file and anonymous volumes
                            attached to containers.
    --remove-orphans        Remove containers for services not defined in the
                            Compose file
    -t, --timeout TIMEOUT   Specify a shutdown timeout in seconds.
                            (default: 10)

例如:


[root@OPS01-LINTEST02 composetest]# docker-compose down
Stopping composetest_web_1   ... done
Stopping composetest_redis_1 ... done
Removing composetest_web_1   ... done
Removing composetest_redis_1 ... done
Removing network composetest_default

[root@OPS01-LINTEST02 composetest]# docker images
# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
composetest_web              latest              531a43261c49        3 hours ago         92.7MB

可以看到容器被删除了,但是镜像还在。


[root@OPS01-LINTEST02 composetest]# docker-compose down --rmi all
Stopping composetest_web_1   ... done
Stopping composetest_redis_1 ... done
Removing composetest_web_1   ... done
Removing composetest_redis_1 ... done
Removing network composetest_default
Removing image composetest_web
Removing image redis:alpine

可以看到镜像也被删除了


event输出docker-compose 事件的日志,当执行docker-compose命令操作时,docker-compose event命令就会监控日志:

Usage: events [options] [SERVICE...]

Options:
    --json      Output events as a stream of json objects



exec和docker exec命令功能相同,可以通过service name登陆到容器中

Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

Options:
    -d, --detach      Detached mode: Run command in the background.  分离模式,后台运行命令
    --privileged      Give extended privileges to the process.  获取特权
    -u, --user USER   Run the command as this user. 指定运行的用户.
    -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                      allocates a TTY.  禁用分配TTY. By default `docker-compose exec` 分配一个TTY.
    --index=index     index of the container if there are multiple
                      instances of a service [default: 1]    当一个服务拥有多个容器时,可通过该参数登陆到该服务下的任何服务,例如:docker-compose exec --index=1 web /bin/bash ,web服务中包含多个容器
    -e, --env KEY=VAL Set environment variables (can be used multiple times,
                      not supported in API < 1.25)

例如:

[root@OPS01-LINTEST02 composetest]# docker-compose config --services
web
redis

[root@OPS01-LINTEST02 composetest]# docker-compose exec web sh
/code # ls
Dockerfile          docker-compose.yml
app.py              requirements.txt


kill通过发送 SIGKILL 信号来强制停止服务容器。支持通过参数来指定发送的信号

Usage: kill [options] [SERVICE...]

Options:
-s SIGNAL         SIGNAL to send to the container. Default signal is SIGKILL.

例如:停止web服务

# docker-compose kill -s SIGKILL web
Killing composetest_web_1 ... done

# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS               NAMES
98ddb468d67a        composetest_web     "python app.py"          7 minutes ago       Exited (137) 4 seconds ago                       composetest_web_1


logs显示日志输出.

Usage: logs [options] [SERVICE...]

Options:
--no-color          Produce monochrome output.
-f, --follow        Follow log output
-t, --timestamps    Show timestamps  显示时间戳
--tail="all"        Number of lines to show from the end of the logs
                    for each container.

例如:

# docker-compose logs
Attaching to composetest_web_1, composetest_redis_1
web_1    |  * Serving Flask app "app" (lazy loading)
web_1    |  * Environment: production
web_1    |    WARNING: Do not use the development server in a production environment.
web_1    |    Use a production WSGI server instead.
web_1    |  * Debug mode: on
web_1    |  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 151-215-059
redis_1  | 1:C 27 Jun 06:47:25.385 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 27 Jun 06:47:25.387 # Redis version=4.0.10, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 27 Jun 06:47:25.387 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1  | 1:M 27 Jun 06:47:25.389 * Running mode=standalone, port=6379.
redis_1  | 1:M 27 Jun 06:47:25.389 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1  | 1:M 27 Jun 06:47:25.389 # Server initialized
redis_1  | 1:M 27 Jun 06:47:25.389 # 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.
redis_1  | 1:M 27 Jun 06:47:25.389 * Ready to accept connections


pause:暂停一个服务容器,处于暂停状态的容器,无法用start命令启动

Usage: pause [SERVICE...]
# docker-compose pause
Pausing composetest_redis_1 ... done
Pausing composetest_web_1   ... done

docker-compose pause  暂停所有服务



port:显示某个容器端口所映射的公共端口

Usage: port [options] SERVICE PRIVATE_PORT

Options:
--protocol=proto  tcp or udp [default: tcp]
--index=index     index of the container if there are multiple
                  instances of a service [default: 1]

例如:

docker-compose port web 5000

0.0.0.0:5000


ps:列出项目中所有容器

sage: ps [options] [SERVICE...]

Options:
-q    Only display IDs

例如: 

# docker-compose ps
       Name                      Command               State            Ports         
--------------------------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Paused   6379/tcp              
composetest_web_1     python app.py                    Paused   0.0.0.0:5000->5000/tcp



pull:拉取服务依赖的镜像

Usage: pull [options] [SERVICE...]

Options:
    --ignore-pull-failures  Pull what it can and ignores images with pull failures. 忽略pull失败的镜像,继续pull其他镜像.
    --parallel              Deprecated, pull multiple images in parallel (enabled by default).
    --no-parallel           Disable parallel pulling.
    -q, --quiet             Pull without printing progress information
    --include-deps          Also pull services declared as dependencies



restart:重启项目中的服务

Usage: restart [options] [SERVICE...]

Options:
-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds. (default: 10)



rm:删除所有(停止状态)的服务容器

Usage: rm [options] [SERVICE...]

Options:
    -f, --force   Don't ask to confirm removal   强制删除
    -s, --stop    Stop the containers, if required, before removing
    -v            Remove any anonymous volumes attached to containers  删除挂载的数据卷



run:在指定服务上指定一个命令

    run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...]
        SERVICE [COMMAND] [ARGS...]

Options:
    -d, --detach          后台运行容器
    --name NAME           为容器指定一个名字
    --entrypoint CMD      CMD 覆盖默认的容器启动指令
    -e KEY=VAL            设置环境变量值,可以多次使用选项来设置多个环境变量
    -l, --label KEY=VAL   Add or override a label (can be used multiple times)
    -u, --user=""         执行容器运行的用户名或UID
    --no-deps             不自动启动关联的服务容器
    --rm                  运行命令后自动删除容器,d默认下将忽略
    -p, --publish=[]      映射容器端口到本地主机
    --service-ports       配置服务端口并映射到本地主机
    --use-aliases         Use the service's network aliases in the network(s) the
                          container connects to.
    -v, --volume=[]       Bind mount a volume (default [])
    -T                    不分配伪TTY,意味着依赖tty的指令将无法运行
    -w, --workdir=""      Working directory inside the container

例如:

# docker-compose run web df -h
Filesystem                Size      Used Available Use% Mounted on
/dev/mapper/docker-253:1-33829585-e7823f93d92cd1917ac0d92d18af82bb437f68af6991a1f47d007a261cc0cd48
                         10.0G    133.8M      9.9G   1% /
tmpfs                    64.0M         0     64.0M   0% /dev
tmpfs                     1.8G         0      1.8G   0% /sys/fs/cgroup
/dev/vda1                25.0G     15.3G      9.7G  61% /code
/dev/vda1                25.0G     15.3G      9.7G  61% /etc/resolv.conf
/dev/vda1                25.0G     15.3G      9.7G  61% /etc/hostname
/dev/vda1                25.0G     15.3G      9.7G  61% /etc/hosts
shm                      64.0M         0     64.0M   0% /dev/shm
tmpfs                    64.0M         0     64.0M   0% /proc/kcore
tmpfs                    64.0M         0     64.0M   0% /proc/keys
tmpfs                    64.0M         0     64.0M   0% /proc/timer_list
tmpfs                    64.0M         0     64.0M   0% /proc/timer_stats
tmpfs                    64.0M         0     64.0M   0% /proc/sched_debug
tmpfs                     1.8G         0      1.8G   0% /proc/scsi
tmpfs                     1.8G         0      1.8G   0% /sys/firmware


scale:设置服务运行的容器个数,通过service=num来设置

Usage: scale [SERVICE=NUM...]

 如:

docker-compose scale web=2 redis=2


start:启动已经存在的服务容器

Usage: start [SERVICE...]


stop:停止处于运行状态的容器服务,但不删除,可以通过docker-compose start再次启动

Usage: stop [options] [SERVICE...]

Options:
-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds (default: 10).


top:显示正在运行的进程

Usage: top [SERVICE...]

例如:


[root@OPS01-LINTEST02 composetest]# docker-compose top
composetest_redis_1
UID    PID    PPID    C   STIME   TTY     TIME         CMD     
---------------------------------------------------------------
100   18915   18888   0   15:39   ?     00:00:00   redis-server
composetest_web_1
UID     PID    PPID    C   STIME   TTY     TIME                 CMD             
--------------------------------------------------------------------------------
root   18909   18880   0   15:39   ?     00:00:00   python app.py               
root   19015   18909   0   15:39   ?     00:00:03   /usr/local/bin/python app.py



unpause:恢复处于暂停状态状态中的服务

Usage: unpause [SERVICE...]



up

Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]

Options:
    -d, --detach               后台运行服务容器
    --no-color                 不使用颜色来区分不同的服务的控制台输出
    --quiet-pull               Pull without printing progress information
    --no-deps                  不启动服务所链接的容器
    --force-recreate           强制重新创建容器,不能与--no-recreate同时使用
    --always-recreate-deps     Recreate dependent containers.
                               Incompatible with --no-recreate.
    --no-recreate              如果容器已经存在,则不重新创建,不能与--force-recreate同时使用
                               them. Incompatible with --force-recreate and -V.
    --no-build                 不自动构建缺失的服务镜像
    --no-start                 创建容器后不启动
    --build                    Build images before starting containers.
    --abort-on-container-exit  Stops all containers if any container was
                               stopped. Incompatible with -d.
    -t, --timeout TIMEOUT      停止容器时候的超时时间,默认是10s
    -V, --renew-anon-volumes   Recreate anonymous volumes instead of retrieving
                               data from the previous containers.
    --remove-orphans           Remove containers for services not defined
                               in the Compose file.
    --exit-code-from SERVICE   Return the exit code of the selected service
                               container. Implies --abort-on-container-exit.
    --scale SERVICE=NUM        Scale SERVICE to NUM instances. Overrides the
                               `scale` setting in the Compose file if present.

改命令十分强大,它将尝试自动完成包括构建镜像,创建服务,启动服务,并关联服务相关容器的一系列操作。链接的服务都将被自动启动,除非已经处于运行状态。

可以说,大部分的时候都可以直接通过该命令来启动一个项目。默认情况下,docker-compose up启动的容器都在前台,控制台打印所有容器的输出信息,可以方便进行调试。

使用-d选项,将后台运行所有容器。如果容器已经存在,则docker-compose up将尝试停止容器,然后重新创建(保持使用volumes-form挂载的卷),以保证新启动的服务匹配最新的docker-compose.yml文件

如果不希望容器被停止并重新创建,使用--no-recreate,这样只会启动处于停止状态的容器,而忽略已经运行的服务。如果用户想要重新部署某个服务,可以使用--no-deps -d 来重新

创建服务并后台停止旧的服务,启动新服务,并不会影响到其依赖的服务