三、应用Docker话-使用docker-compose部署应用

1、介绍

  • Docker-Compose项目是Docker官方的开源项目,负责实现对Docker容器集群的快速编排。Compose允许用户通过一个单独的docker-compose.yml模板文件(YAML 格式)来定义一组相关联的应用容器为一个项目(project)。Docker-Compose项目由Python编写,调用Docker服务提供的API来对容器进行管理。因此,只要所操作的平台支持Docker API,就可以在其上利用Compose来进行编排管理。
  • Docker-Compose运行目录下的所有文件(docker-compose.yml,extends文件或环境变量文件等)组成一个工程,若无特殊指定工程名即为当前目录名。一个工程当中可包含多个服务,每个服务中定义了容器运行的镜像,参数,依赖。一个服务当中可包括多个容器实例。

2、模版文件

Compose模板文件是一个定义服务、网络和卷的YAML文件。Compose模板文件默认路径是当前目录下的docker-compose.yml,可以使用.yml或.yaml作为文件扩展名, 包含version、services、networks 三大部分,最关键的是services和networks两个部分。

version: '3.7'
services:
  service-name:                                  服务名称
    image: image-name                            镜像名称
    ports:
      - "8081:80"                                端口映射
    volumes:
      - /path/to/file:/path/to/container/file    挂载文件

3、命令

[root@WEB001 docker-sample]# docker-compose
Define and run multi-container applications with Docker.

Usage:
  docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  -f, --file FILE             Specify an alternate compose file
                              (default: docker-compose.yml)
  -p, --project-name NAME     Specify an alternate project name
                              (default: directory name)
  --verbose                   Show more output
  --log-level LEVEL           Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  --no-ansi                   Do not print ANSI control characters
  -v, --version               Print version and exit
  -H, --host HOST             Daemon socket to connect to

  --tls                       Use TLS; implied by --tlsverify
  --tlscacert CA_PATH         Trust certs signed only by this CA
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  --tlskey TLS_KEY_PATH       Path to TLS key file
  --tlsverify                 Use TLS and verify the remote
  --skip-hostname-check       Don't check the daemon's hostname against the
                              name specified in the client certificate
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the Compose file)
  --compatibility             If set, Compose will attempt to convert deploy
                              keys in v3 files to their non-Swarm equivalent

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
  images             List images
  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

docker-compose命令说明

docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  • -f,–file FILE指定Compose模板文件,默认为docker-compose.yml,可以多次指定。
  • -p,–project-name NAME指定项目名称,默认将使用所在目录名称作为项目名。
  • -verbose 输出更多调试信息
  • --log-level LEVEL 设置日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  • --project-directory PATH 工程目录,默认当前目录

docker-compose up命令说明

[root@app]# docker-compose up -h
Builds, (re)creates, starts, and attaches to containers for a service.
Unless they are already running, this command also starts any linked services.
The `docker-compose up` command aggregates the output of each container. When
the command exits, all containers are stopped. Running `docker-compose up -d`
starts the containers in the background and leaves them running.
If there are existing containers for a service, and the service's configuration
or image was changed after the container's creation, `docker-compose up` picks
up the changes by stopping and recreating the containers (preserving mounted
volumes). To prevent Compose from picking up changes, use the `--no-recreate`
flag.

If you want to force Compose to stop and recreate all containers, use the
`--force-recreate` flag.

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

Options:
    -d, --detach               Detached mode: Run containers in the background,
                               print new container names. Incompatible with
                               --abort-on-container-exit.
    --no-color                 Produce monochrome output.
    --quiet-pull               Pull without printing progress information
    --no-deps                  Don't start linked services.
    --force-recreate           Recreate containers even if their configuration
                               and image haven't changed.
    --always-recreate-deps     Recreate dependent containers.
                               Incompatible with --no-recreate.
    --no-recreate              If containers already exist, don't recreate
                               them. Incompatible with --force-recreate and -V.
    --no-build                 Don't build an image, even if it's missing.
    --no-start                 Don't start the services after creating them.
    --build                    Build images before starting containers.
    --abort-on-container-exit  Stops all containers if any container was
                               stopped. Incompatible with -d.
    -t, --timeout TIMEOUT      Use this timeout in seconds for container
                               shutdown when attached or when containers are
                               already running. (default: 10)
    -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.

运行服务容器

  • -d 在后台运行服务容器
  • –no-color 不使用颜色来区分不同的服务的控制输出
  • –no-deps 不启动服务所链接的容器
  • –force-recreate 强制重新创建容器,不能与–no-recreate同时使用
  • –no-recreate 如果容器已经存在,则不重新创建,不能与–force-recreate同时使用
  • –no-build 不自动构建缺失的服务镜像
  • –build 在启动容器前构建服务镜像
  • –abort-on-container-exit 停止所有容器,如果任何一个容器被停止,不能与-d同时使用
  • -t, –timeout TIMEOUT 停止容器时候的超时(默认为10秒)
  • –remove-orphans 删除服务中没有在compose文件中定义的容器
  • –scale SERVICE=NUM 设置服务运行容器的个数,将覆盖在compose中通过scale指定的参数

docker-compose down命令说明

[root@app]# docker-compose down -h
Stops containers and removes containers, networks, volumes, and images
created by `up`.

By default, the only things removed are:

- Containers for services defined in the Compose file
- Networks defined in the `networks` section of the Compose file
- The default network, if one is used

Networks and volumes defined as `external` are never removed.

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)

停止和删除容器、网络、卷、镜像

  • –rmi type,删除镜像,类型必须是:all,删除compose文件中定义的所有镜像;local,删除镜像名为空的镜像
  • -v, –volumes,删除已经在compose文件中定义的和匿名的附在容器上的数据卷
  • –remove-orphans,删除服务中没有在compose中定义的容器

4、docker-compose应用案例

接上节docker-sample项目案例,创建docker-compose.yml模板文件

[root@docker-sample]# vi docker-compose.yml 

version: '3.7'
services:
  docker-app:
    image: giself/docker-app:1.0.0                //镜像名称
    privileged: true                              //设置容器的权限为root
    restart: always                               //关机或者重启docker同时重启容器
    ports:
      - "8081:8081"                               //宿主机和容器端口映射

目录结构如下

[root@docker-sample]# ll
total 16688
-rw-r--r-- 1 root root     1853 Apr  8 19:55 build.sh
-rw-r--r-- 1 root root 17065044 Apr  2 16:39 docker-app-1.0.0.jar
-rw-r--r-- 1 root root      638 Apr  8 19:52 docker-compose.yml
-rw-r--r-- 1 root root      310 Apr  8 19:52 Dockerfile

修改build.sh脚本文件

#启动容器
echo "启动容器..."
#docker run -d -p $port:$port $image_name:$version
docker-compose up -d
#查询容器

到这里就可以使用 sh build.sh 生成镜像,运行容器了。大家有可能发现了一个问题,build.sh中已配置了项目名称,映射端口,模板文件还需要再次配置,有参数变更,模板文件忘记修改就会造成不一致。这个问题可以通过配置docker-compose-sample.yml文件,参数替换动态生成docker-compose.yml文件的方式解决

docker-compose-sample.yml

[root@docker-sample]# cat docker-compose-sample.yml 
version: '3.7'
services:
  _APP_NAME_:
    image: _PROJ_NAME_/_APP_NAME_:1.0.0
    privileged: true
    restart: always
    ports:
      - "_PORT_:_PORT_"

完整build.sh如下

#!/bin/sh
cd /data/app/docker-sample
proj_name=giself
app_name=docker-app
version="1.0.0"
port=8081
image_name="$proj_name/$app_name"

container_id=`docker ps -aq --filter ancestor=$image_name:$version`
echo "镜像 $image_name 容器id= $container_id"
if [ ! $container_id ]; then
  echo "容器不存在,无需删除"
else
  #停止容器
  docker stop $container_id
  docker rm $container_id
  echo "删除容器 $container_id"
fi

#查询镜像
image_id=`docker images -q $image_name`
echo "镜像 $image_name 镜像id= $image_id"
if [ ! $image_id ]; then
  echo "镜像不存在,无需删除"
else
  docker rmi $image_id
  echo "删除镜像 $image_id"
fi
#构建镜像
echo "构建镜像..."
docker build -t $image_name:$version .
#启动容器
echo "启动容器..."
rm -rf ./docker-compose.yml
cp ./docker-compose-sample.yml ./docker-compose.yml
sed -i "s/_PROJ_NAME_/${proj_name}/g" ./docker-compose.yml
sed -i "s/_APP_NAME_/${app_name}/g" ./docker-compose.yml
sed -i "s/_PORT_/${port}/g" ./docker-compose.yml
docker-compose up -d
#查询容器
container_id=`docker ps -aq --filter ancestor=$image_name:$version`
echo "启动镜像 $image_name 容器id= $container_id"

#查看日志
#docker logs --tail="500" $container_id

下一篇,讲解Docker化微服务注册到Eureka中eureka.instance问题

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容