Docker-compose简介

Docker-Compose项目是Docker官方的开源项目,负责实现对Docker容器集群的快速编排。

Docker-Compose将所管理的容器分为三层,分别是工程(project),服务(service)以及容器(container)。Docker-Compose运行目录下的所有文件(docker-compose.yml,extends文件或环境变量文件等)组成一个工程,若无特殊指定工程名即为当前目录名。一个工程当中可包含多个服务,每个服务中定义了容器运行的镜像,参数,依赖。一个服务当中可包括多个容器实例,Docker-Compose并没有解决负载均衡的问题,因此需要借助其它工具实现服务发现及负载均衡。
Docker-Compose的工程配置文件默认为docker-compose.yml,可通过环境变量COMPOSE_FILE或-f参数自定义配置文件,其定义了多个有依赖关系的服务及每个服务运行的容器。

使用一个Dockerfile模板文件,可以让用户很方便的定义一个单独的应用容器。在工作中,经常会碰到需要多个容器相互配合来完成某项任务的情况。例如要实现一个Web项目,除了Web服务容器本身,往往还需要再加上后端的数据库服务容器,甚至还包括负载均衡容器等。Compose允许用户通过一个单独的docker-compose.yml模板文件(YAML 格式)来定义一组相关联的应用容器为一个项目(project)。

Docker-Compose项目由Python编写,调用Docker服务提供的API来对容器进行管理。因此,只要所操作的平台支持Docker API,就可以在其上利用Compose来进行编排管理。

Compose使用的三个步骤:

  1. 使用Dockerfile定义应用程序的环境。
  2. 使用docker-compose.yml定义构成应用程序的服务,这样它们可以在隔离环境中一起运行。
  3. 最后,执行docker-compose up命令来启动并运行整个应用程序。

Docker-compose的安装

安装环境:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal

直接apt命令安装:

$ sudo apt install docker-compose
... ...
$ docker-compose -v
docker-compose version 1.25.0, build unknown

简单使用

  1. 创建docker-compose.yml,内容如下:
version: '2'
services:web1:image: nginxports:- "6061:80"container_name: "nginx1"networks:- ngweb2:image: nginxports:- "6062:80"container_name: "nginx2"networks:- ngnetworks:ng:driver: bridge
  1. 启动应用
$ docker-compose up

然后就可以在浏览器访问nginx了,是不是很方便!!!

Docker-compose常用命令

Docker-compose命令格式

$ docker-compose -h
Define and run multi-container applications with Docker.Usage:docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]docker-compose -h|--helpOptions:-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 thename 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 keysin v3 files to their non-Swarm equivalent--env-file PATH             Specify an alternate environment fileCommands:build              Build or rebuild servicesbundle             Generate a Docker bundle from the Compose fileconfig             Validate and view the Compose filecreate             Create servicesdown               Stop and remove containers, networks, images, and volumesevents             Receive real time events from containersexec               Execute a command in a running containerhelp               Get help on a commandimages             List imageskill               Kill containerslogs               View output from containerspause              Pause servicesport               Print the public port for a port bindingps                 List containerspull               Pull service imagespush               Push service imagesrestart            Restart servicesrm                 Remove stopped containersrun                Run a one-off commandscale              Set number of containers for a servicestart              Start servicesstop               Stop servicestop                Display the running processesunpause            Unpause servicesup                 Create and start containersversion            Show the Docker-Compose version information

docker-compose up

启动服务:

$ 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 configurationand image haven't changed.--always-recreate-deps     Recreate dependent containers.Incompatible with --no-recreate.--no-recreate              If containers already exist, don't recreatethem. 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 wasstopped. Incompatible with -d.-t, --timeout TIMEOUT      Use this timeout in seconds for containershutdown when attached or when containers arealready running. (default: 10)-V, --renew-anon-volumes   Recreate anonymous volumes instead of retrievingdata from the previous containers.--remove-orphans           Remove containers for services not definedin the Compose file.--exit-code-from SERVICE   Return the exit code of the selected servicecontainer. 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
Starting nginx1 ... done
Starting nginx2 ... done

docker-compose ps

命令格式如下:

$ docker-compose ps -h
List containers.Usage: ps [options] [SERVICE...]Options:-q, --quiet          Only display IDs--services           Display services--filter KEY=VAL     Filter services by a property-a, --all            Show all stopped containers (including those created by the run command)

使用如下:

$ docker-compose psName               Command               State                  Ports--------------------------------------------------------------------------------------
nginx1   /docker-entrypoint.sh ngin ...   Up      0.0.0.0:6061->80/tcp,:::6061->80/tcp
nginx2   /docker-entrypoint.sh ngin ...   Up      0.0.0.0:6062->80/tcp,:::6062->80/tcp

docker-compose stop

命令格式如下:

$ docker-compose stop -h
Stop running containers without removing them.They can be started again with `docker-compose start`.Usage: stop [options] [SERVICE...]Options:-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.(default: 10)

使用如下:

$ docker-compose stop
Stopping nginx2 ... done
Stopping nginx1 ... done

docker-compose down

命令格式如下:

$ 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 usedNetworks 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 acustom tag set by the `image` field.-v, --volumes           Remove named volumes declared in the `volumes`section of the Compose file and anonymous volumesattached to containers.--remove-orphans        Remove containers for services not defined in theCompose file-t, --timeout TIMEOUT   Specify a shutdown timeout in seconds.(default: 10)

使用如下:

t$ docker-compose down
Stopping nginx2 ... done
Stopping nginx1 ... done
Removing nginx2 ... done
Removing nginx1 ... done
Removing network test_ng

docker-compose logs

命令格式如下:

$ docker-compose logs -h
View output from containers.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 logsfor each container.

使用如下:

$ docker-compose logs -f
... ...

docker-compose bulid

命令格式如下:

$ docker-compose build -h
Build or rebuild services.Services are built once and then tagged as `project_service`,
e.g. `composetest_db`. If you change a service's `Dockerfile` or the
ontents of its build directory, you can run `docker-compose build` to rebuild it.Usage: build [options] [--build-arg key=val...] [SERVICE...]Options:--build-arg key=val     Set build-time variables for services.--compress              Compress the build context using gzip.--force-rm              Always remove intermediate containers.-m, --memory MEM        Set memory limit for the build container.--no-cache              Do not use cache when building the image.--no-rm                 Do not remove intermediate containers after a successful build.--parallel              Build images in parallel.--progress string       Set type of progress output (auto, plain, tty).EXPERIMENTAL flag for native builder.To enable, run with COMPOSE_DOCKER_CLI_BUILD=1)--pull                  Always attempt to pull a newer version of the image.-q, --quiet             Don't print anything to STDOUT

使用如下:

$ cat docker-compose.yml
version: '2'
services:web:build:dockerfile: redis.dockerfilecontext: .ports:- "6379:6379"container_name: "redis"networks:- redisnetworks:redis:driver: bridge$ docker-compose build
Building web
... ...

docker-compose pull

命令格式如下:

$ docker-compose pull -h
Pulls images for services defined in a Compose file, but does not start the containers.Usage: pull [options] [SERVICE...]Options:--ignore-pull-failures  Pull what it can and ignores images with pull failures.--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

使用如下:

$ docker-compose pull
Pulling web1 ... done
Pulling web2 ... done

docker-compose restart

命令格式如下:

$ docker-compose restart -h
Restart running containers.Usage: restart [options] [SERVICE...]Options:-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.(default: 10)

使用如下:

$ docker-compose restart
Restarting nginx2 ... done
Restarting nginx1 ... done

docker-compose rm

命令格式如下:

$ docker-compose rm -h
Removes stopped service containers.By default, anonymous volumes attached to containers will not be removed. You
can override this with `-v`. To list all volumes, use `docker volume ls`.Any data which is not in a volume will be lost.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-a, --all     Deprecated - no effect.

使用如下:

$ docker-compose rm
Going to remove nginx2, nginx1
Are you sure? [yN] y
Removing nginx2 ... done
Removing nginx1 ... done

docker-compose start

命令格式如下:

$ docker-compose start -h
Start existing containers.Usage: start [SERVICE...]

使用如下:

$ docker-compose start
Starting web1 ... done
Starting web2 ... done

docker-compose run

命令格式如下:

$ docker-compose run -h
Run a one-off command on a service.For example:$ docker-compose run web python manage.py shellBy default, linked services will be started, unless they are already
running. If you do not want to start linked services, use
`docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.Usage:run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...]SERVICE [COMMAND] [ARGS...]Options:-d, --detach          Detached mode: Run container in the background, printnew container name.--name NAME           Assign a name to the container--entrypoint CMD      Override the entrypoint of the image.-e KEY=VAL            Set an environment variable (can be used multiple times)-l, --label KEY=VAL   Add or override a label (can be used multiple times)-u, --user=""         Run as specified username or uid--no-deps             Don't start linked services.--rm                  Remove container after run. Ignored in detached mode.-p, --publish=[]      Publish a container's port(s) to the host--service-ports       Run command with the service's ports enabled and mappedto the host.--use-aliases         Use the service's network aliases in the network(s) thecontainer connects to.-v, --volume=[]       Bind mount a volume (default [])-T                    Disable pseudo-tty allocation. By default `docker-compose run`allocates a TTY.-w, --workdir=""      Working directory inside the container

使用如下:

$ docker-compose run web1
... ...

docker-compose scale

命令格式如下:

$ docker-compose scale -h
Set number of containers to run for a service.Numbers are specified in the form `service=num` as arguments.
For example:$ docker-compose scale web=2 worker=3This command is deprecated. Use the up command with the `--scale` flag
instead.Usage: scale [options] [SERVICE=NUM...]Options:-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.(default: 10)

使用如下:

$ cat docker-compose.yml
version: '2'services:web:image: nginxlb:image: dockercloud/haproxylinks:- webports:- 8080:80volumes:- /var/run/docker.sock:/var/run/docker.sock$ docker-compose up --scale web=2

docker-compose pause

命令格式如下:

$ docker-compose pause -h
Pause services.Usage: pause [SERVICE...]

使用如下:

$ docker-compose pause
Pausing nginx1 ... done
Pausing nginx2 ... done

docker-compose kill

命令格式如下:

$ docker-compose kill -h
Force stop service containers.Usage: kill [options] [SERVICE...]Options:-s SIGNAL         SIGNAL to send to the container.Default signal is SIGKILL.

使用如下:

$ docker-compose kill
Killing nginx1 ... done
Killing nginx2 ... done

docker-compose config

命令格式如下:

$ docker-compose config -h
Validate and view the Compose file.Usage: config [options]Options:--resolve-image-digests  Pin image tags to digests.--no-interpolate         Don't interpolate environment variables-q, --quiet              Only validate the configuration, don't printanything.--services               Print the service names, one per line.--volumes                Print the volume names, one per line.--hash="*"               Print the service config hash, one per line.Set "service1,service2" for a list of specified servicesor use the wildcard symbol to display all services

使用如下:

$ docker-compose config
networks:ng:driver: bridge
services:web1:container_name: nginx1image: nginxnetworks:ng: nullports:- 6061:80/tcpweb2:container_name: nginx2image: nginxnetworks:ng: nullports:- 6062:80/tcp
version: '2.0'

docker-compose create

命令格式如下:

$ docker-compose create -h
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 andimage 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.

docker-compose exec

命令格式如下:

$ docker-compose exec -h
Execute a command in a running containerUsage: 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.--index=index     index of the container if there are multipleinstances of a service [default: 1]-e, --env KEY=VAL Set environment variables (can be used multiple times,not supported in API < 1.25)-w, --workdir DIR Path to workdir directory for this command.

使用如下:

$ docker-compose exec web1 bash
root@edf71f8788f4:/#

docker-compose port

命令格式如下:

$ docker-compose port -h
Print the public port for a port binding.Usage: port [options] SERVICE PRIVATE_PORTOptions:--protocol=proto  tcp or udp [default: tcp]--index=index     index of the container if there are multipleinstances of a service [default: 1]

使用如下:

$ docker-compose port web1 80
0.0.0.0:6061

docker-compose push

命令格式如下:

$ docker-compose push -h
Pushes images for services.Usage: push [options] [SERVICE...]Options:--ignore-push-failures  Push what it can and ignores images with push failures.

docker-compose uppause

命令格式如下:

$ docker-compose unpause -h
Unpause services.Usage: unpause [SERVICE...]

使用如下:

$ docker-compose unpause
Unpausing nginx2 ... done
Unpausing nginx1 ... done

遇到的问题

  1. 错误:docker.credentials.errors.InitializationError: docker-credential-desktop.exe not installed or not available in PATH

执行如下命令即可:

$ rm ~/.docker/config.json

Docker Compose的安装与使用相关推荐

  1. Docker Compose方式安装GitLab

    文章目录 用Docker Compose方式安装GitLab 前提条件 一键自动化以Docker Compose方式安装GitLab GitLab Docker Compose文件 安装和运行GitL ...

  2. 阿里云服务器Docker及Docker Compose的安装

    2019独角兽企业重金招聘Python工程师标准>>> 本文对阿里云ECS服务器如何安装Docker和Docker Compose进行说明,以centOS系统为例. 一.开通外网的E ...

  3. docker compose linux安装以及使用

    1 安装 Compose 安装 Linux Linux 上我们可以从 Github 上下载它的二进制包来使用,最新发行的版本地址:https://github.com/docker/compose/r ...

  4. Docker与Docker Compose的安装以及Portainer容器管理工具

    Docker官网 概述 Docker 是一个用于开发.发布和运行应用程序的开放平台.Docker 能够将应用程序与基础架构分离,以便可以快速交付软件.使用 Docker,可以像管理应用程序一样管理基础 ...

  5. docker Compose 下载安装

    在linux上 请注意,Compose standalone 使用-compose语法而不是当前的标准语法compose. 例如docker-compose up,在使用 Compose standa ...

  6. 1.2 win10下Docker 和 Docker Compose的安装

    参考步骤 中文: https://www.runoob.com/docker/windows-docker-install.html 英文官网: https://docs.docker.com/doc ...

  7. Docker Compose安装

    一 .  Docker Compose概述 Docker Compose是一个用于定义和运行多个容器Docker应用程序的工具.使用Compose,您可以使用YAML文件来配置应用程序的服务.然后 , ...

  8. Docker Compose安装以及入门

    Docker 安装 脚本安装 自定义脚本 wget https://mirrors.aliyun.com/docker-ce/linux/centos/7/x86_64/stable/Packages ...

  9. 04@Docker Compose安装Compose模板文件的使用

    文章目录 Docker Compose 一.Docker Compose的介绍 1.Compose概述 2.Docker与Docker Compose区别 二.Docker Compose的安装 1. ...

最新文章

  1. 脑机相连的狂想,马斯克实现了吗?智源观点:还很遥远
  2. 烂泥:kickstart无人值守安装CentOS6.5
  3. 分层应用——怎样实现登录?
  4. win10 远程登录 每次需要输密码
  5. 如何配置pom.xml用maven打包java工程
  6. PAT (Basic Level) Practice (中文)1011 A+B 和 C (15 分)
  7. 多项式相乘与相加演示
  8. RTMP协议发送H.264编码及AAC编码的音视频,实现摄像头直播
  9. java程序退出自动保存_你知道如何自动保存 Spring Boot 应用进程号吗
  10. 计算机考研分析题,2020计算机考研,易错题分析与常考点总结
  11. pulsar 著名的开源消息传递系统
  12. PAT-A1025 PAT Ranking
  13. ehtools:一款WiFi渗透框架
  14. 最新VmWare14激活序列号
  15. 通用印刷体文字识别_印刷体文字识别(汉字)中文符的分割
  16. 计算机怎么禁止远程桌面,win7怎样禁用远程桌面共享_win7系统禁用远程桌面共享的步骤-系统城...
  17. nmap超快高效扫描端口
  18. 读取UYVY格式的YUV图片,并转为RGB格式
  19. 汽车驾驶 - 道路交通标线和标志
  20. python键盘上下左右控制_【322】python控制键盘鼠标:pynput

热门文章

  1. popper.js 使用
  2. Baklib电子产品手册制作,简单且实用
  3. linux socket eof,Linux 中的 EOF 到底是什么?
  4. 本地Host文件解析域名后访问阿里云服务器, 结果请求被拦截, 提示备案问题的解决方式
  5. 【Docker】五 Docker Hub管理镜像
  6. 今日份不一样的早餐!
  7. 谷歌开源基于 ML 的手部跟踪算法
  8. Unity 报错之 The same field name is serialized multiple times in the class or its parent class.
  9. 谷歌借力AlphaGo造大模型,称其秒杀ChatGPT!
  10. 如何实现多风格选择样式实时切换?