docker-compose Introduction

A, Docker-Compose Profile

  Docker Docker-Compose official project is an open source project, responsible for fast layout of Docker container cluster.
  The management Docker-Compose container is divided into three, respectively 工程(project), 服务(service)as well 容器(container).
  All files (docker-compose.yml, extends file or environment variable file, etc.) in Docker-Compose run up a project directory, in the absence of special designated project name is the name of the current directory. A project which may comprise a plurality of services, each defined image container runs, parameters dependent. A service which may include multiple container instance, Docker-Compose does not solve the problem of load balancing, and therefore need to use other tools to achieve service discovery and load balancing.
  Docker-Compose project configuration files by default docker-compose.yml, can COMPOSE_FILE through the environment variable or -f parameter custom configuration file, which defines several services that depend on each service and run a container.
  Dockerfile use a template file, allowing users to easily define a single application container. At work, often encounter case to complete a task requiring multiple containers with each other. For example, to implement a Web project, in addition to Web services container itself, often also need to add the back-end database services container, even including load balancing containers.
  Compose application allows the user to define a group of containers associated by a single docker-compose.yml template file (YAML format) for a project (project).
  Docker-Compose project written by Python, call the API Docker service provided to manage the container. Therefore, as long as the operating platform to support Docker API, you can manage to orchestrate use Compose thereon.
Documents Address:https://docs.docker.com/compose/reference/build/

 

Two, Docker-Compose installation

# 下载Docker-Compose
[root@topcheer ~]# curl -L https://github.com/docker/compose/releases/download/1.25.0-rc2/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
#  Docker-Compose
[root@topcheer bin]# sudo chmod +x /usr/local/bin/docker-compose
[root@topcheer bin]# docker-compose version
docker-compose version 1.24.1, build 4667896b
docker-py version: 3.7.3
CPython version: 3.6.8
OpenSSL version: OpenSSL 1.1.0j  20 Nov 2018

Three, Docker-Compose command

1, Docker-Compose Format

docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]

Command options are as follows:
-f, -file FILE specify Compose a template file, the default is docker-compose.yml, can be specified multiple times.
-p, -project-name NAME specify the project name, the default directory name will be used as the project name.
Docker network using the back-end characteristics pluggable -x-network-driver (version requires Docker 1.9+)
driving -x-network-driver DRIVER backend network specified, the default is Bridge (version requires Docker 1.9+)
-verbose more output multi debugging information
-v, -version Print version and exit

2、docker-compose up

docker-compose up [options] [--scale SERVICE=NUM...] [SERVICE...]

The options are:
-d container service running in the background
without the use of color -no-color to distinguish between different services control output
container -no-deps not start the service linked
-force-recreate forced to re-create the container, not with -no- recreate use
-no-recreate If the container already exists, it is not re-created, can not be used with the -force-recreate
service mirroring -no-build does not automatically build missing
-build mirror before starting to build a service container
-abort-on- container-exit stop all container, a container is stopped if any, can not be used in conjunction with -d
-t, -timeout tIMEOUT timeout to stop container time (default is 10 seconds)
-remove-Orphans delete a service is not defined in the compose documents the container
-scale sERVICE = number of container set the service to run NUM, will compose the scale covering parameters specified by the
docker-compose up
start all the services
docker-compose up -d
in the background all start the service
-f specify the Compose a template file, the default is docker-compose.yml, You can specify multiple times.
docker-compose -f docker-compose.yml up -d

[root@topcheer docker]# docker-compose up -d
Creating network "docker_default" with the default driver
Pulling web1 (nginx:)...
Trying to pull repository docker.io/library/nginx ...
latest: Pulling from docker.io/library/nginx
000eee12ec04: Pull complete
eb22865337de: Pull complete
bee5d581ef8b: Pull complete
Digest: sha256:50cf965a6e08ec5784009d0fccb380fc479826b6e0e65684d9879170a9df8566
Status: Downloaded newer image for docker.io/nginx:latest
Creating web1 ... done
Creating web2 ... done

3、docker-compose ps

docker-compose ps [options] [SERVICE...]
docker-compose ps
All items listed in the current container

[root@topcheer docker]# docker-compose ps
Name         Command          State          Ports
----------------------------------------------------------
web1   nginx -g daemon off;   Up      0.0.0.0:6061->80/tcp
web2   nginx -g daemon off;   Up      0.0.0.0:6062->80/tcp
[root@topcheer docker]#

4、docker-compose stop

docker-compose stop [options] [SERVICE...]
Options include:
-t, -timeout TIMEOUT timeout to stop container time (default is 10 seconds)
docker-compose stop
stop the container is running, you can start again by docker-compose start

[root@topcheer docker]# docker-compose stop
Stopping web2 ... done
Stopping web1 ... done
[root@topcheer docker]# docker-compose start
Starting web1 ... done
Starting web2 ... done

5、docker-compose -h

docker-compose -h
View Help

[root@topcheer docker]# docker-compose -h
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 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
[root@topcheer docker]#

6、docker-compose down

docker-compose down [options]
Stop and remove container, network volumes, mirrored.
Options include:
-rmi of the type, remove the mirror, the type must be: all, all mirrored delete compose defined in the file; local, remove the mirror image called empty
-v, -volumes, delete the already defined in the file and compose Anonymous data volume on the attached container
-remove-orphans, remove the service is not defined in the compose container
docker-compose down
deactivate and remove all container network-related

7、docker-compose logs

docker-compose logs [options] [SERVICE...]
View the output service container. By default, docker-compose the output will be different services use different colors to distinguish. Color can be closed by -no-color.
docker-compose logs
Look at the output of the service vessel

[root@topcheer docker]# docker-compose logs -t -f --tail 20
Attaching to web2, web1
web2    | 2019-11-28T07:53:24.031166000Z 192.168.180.1 - - [28/Nov/2019:07:53:24 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" "-"
web2    | 2019-11-28T07:53:24.054396000Z 2019/11/28 07:53:24 [error] 7#7: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.180.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.180.113:6062", referrer: "http://192.168.180.113:6062/"
web2    | 2019-11-28T07:53:24.060006000Z 192.168.180.1 - - [28/Nov/2019:07:53:24 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.180.113:6062/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" "-"
web1    | 2019-11-28T07:53:19.115374000Z 192.168.180.1 - - [28/Nov/2019:07:53:19 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" "-"
web1    | 2019-11-28T07:53:19.326008000Z 192.168.180.1 - - [28/Nov/2019:07:53:19 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.180.113:6061/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" "-"
web1    | 2019-11-28T07:53:19.326377000Z 2019/11/28 07:53:19 [error] 7#7: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.180.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.180.113:6061", referrer: "http://192.168.180.113:6061/"

8、docker-compose build

docker-compose build [options] [--build-arg key=val...] [SERVICE...]
Building (rebuilding) service container project.
Options include:
-compress gzip compression by constructing upper and lower environmental
-force-rm delete build temporary container during
-no-cache building process does not use mirrored cache
-pull always try to get an updated version of the image by the action of pulling
-m, -memory MEM container is provided for the construction of the memory size
-build-arg key = val service provided build-time variable
service container once constructed, will bring a tag name. You can always run docker-compose build under the project to rebuild the directory service

9、docker-compose pull

docker-compose pull [options] [SERVICE...]
Pull service dependent mirror.
Options include:
-ignore-pull-failures, ignore the error pull mirroring process
-parallel, multiple mirror while pulling
-quiet, pull mirroring process does not print progress information
docker-compose pull
pull service dependent mirror

10、docker-compose restart

docker-compose restart [options] [SERVICE...]
Restart project services.
Options include:
-t, -timeout before TIMEOUT, specify the restart timeout to stop the vessel (the default is 10 seconds)
docker-compose restart
to restart the project in the service

11、docker-compose rm

docker-compose rm [options] [SERVICE...]
Delete all service container (stop state).
The options are:
-f, -force, forced to delete, including non-stop state of the container
-v, delete container mounted data volumes
docker-compose rm
to delete all service container (stop state). It is recommended to perform docker-compose stop command to stop the vessel.

12、docker-compose start

docker-compose start [SERVICE...]
docker-compose start
Start the service container that already exists.

13、docker-compose run

docker-compose run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
Execute a command on the specified service.
docker-compose run ubuntu ping www.baidu.com
Execute a ping command in the specified container.

14、docker-compose scale

docker-compose scale web=3 db=2
Set the number of containers specified service running. To set the number of parameters by num service =

15、docker-compose pause

docker-compose pause [SERVICE...]
Pause a service container

16、docker-compose kill

docker-compose kill [options] [SERVICE...]
By sending a signal to forcibly stop the services SIGKILL container. 
Support signal transmitted through -s specified parameters, such as command transmitting SIGINT signal by:
docker-compose kill -s SIGINT

17, consists dokcer-config

docker-compose config [options]
Verify compose and view the file configuration.
Options include:
-resolve-Image-Digests it is possible to label image labeled as a digest
-q, -quiet only verify the configuration, is not output. When properly configured, does not output anything, when the file configuration errors, output an error message
-services print service name, one per line

[root@topcheer docker]# docker-compose config -q
[root@topcheer docker]# 


-volumes print data volume name, one per line

18、docker-compose create

docker-compose create [options] [SERVICE...]
Create a container for the service.
Options include:
-force-recreate: to re-create the container, even if the configuration has not changed and mirrors, is not compatible with -no-recreate parameters
-no-recreate: If the container already exists, do not need to re-create, is not compatible with -force-recreate parameters
-no -build: Do not create a mirror, even if the lack of
-build: create a container before, generated image

19、docker-compose exec

docker-compose exec [options] SERVICE COMMAND [ARGS...]
The options are:
-d separate mode, command running in the background.
-Privileged get privileges.
-User USER Specifies the user runs.
-T Disable allocation TTY, default docker-compose exec assignment TTY.
-Index = index, when a service has a plurality of containers, this parameter can be found to any service in the service, for example: docker-compose exec -index = 1 web / bin / bash, web service comprising a plurality of containers

20、docker-compose port

docker-compose port [options] SERVICE PRIVATE_PORT
Public display port a container port mapping.
Options include:
--protocol = proto, designated port protocol, TCP (default) or UDP
-index = index, if you agree there are multiple service containers, container specified number of command object (default is 1)

21、docker-compose push

docker-compose push [options] [SERVICE...]
Push service according to the Mirror.
Options include:
-ignore the Push-push-mirroring process failures ignore errors

22、docker-compose stop

docker-compose stop [options] [SERVICE...]
Display case each container process running.

23、docker-compose unpause

docker-compose unpause [SERVICE...]
Restore service in a suspended state.

24、docker-compose version

docker-compose version
Print version information

[root@topcheer docker]# docker-compose version
docker-compose version 1.24.1, build 4667896b
docker-py version: 3.7.3
CPython version: 3.6.8
OpenSSL version: OpenSSL 1.1.0j  20 Nov 2018
[root@topcheer docker]#

Four, Docker-Compose a template file

1, Docker-Compose profile template file
  Compose allow a user docker-compose.yml a template file (YAML format) to define a set of applications associated with the container for a project (project).
  Compose a template file is the definition of service, and network volumes YAML file. Compose a template file in the default path is docker-compose.yml in the current directory, you can use .yml or .yaml as the file extension.
  Docker-Compose standard template file should contain version , services , networks three parts, the most critical services and networks is in two parts.
version: '2'
services:
  web:
    image: dockercloud/hello-world
    ports:
      - 8080
    networks:
      - front-tier
      - back-tier

  redis:
    image: redis
    links:
      - web
    networks:
      - back-tier

  lb:
    image: dockercloud/haproxy
    ports:
      - 80:80
    links:
      - web
    networks:
      - front-tier
      - back-tier
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock 

networks:
  front-tier:
    driver: bridge
  back-tier:
    driver: bridge

Compose There are three versions Version 1, Version 2, Version 3 , Compose distinguish Version 1 and Version 2 (Compose 1.6.0 +, Docker Engine 1.10.0+). Version 2 supports more instructions. Version 1 will be abandoned in the future.
2, Image
  Image is a mirror image name or ID specified services. If the mirror does not exist locally, Compose will try to pull the mirror.

services: 
    web: 
        image: hello-world

3, build
service in addition based on the specified image can also be based on a Dockerfile, while using up to start the implementation of building tasks, build tag is build, you can specify the path to the folder where Dockerfile. Compose use Dockerfile will automatically build the mirror, and then use the image to start the service container.
build: / path / to / build / dir
may be a relative path, as long as it can read the context determination Dockerfile.

build: ./dir

Setting context root, and then subject to the specified directory Dockerfile.

build:
  context: ../
  dockerfile: path/of/Dockerfile

build is a directory, if you want to specify Dockerfile file needs to specify the use of dockerfile tag in the child tag build tag.
If you specify the image and build two labels at the same time, the Compose builds mirror and the mirror image name specified value name.

4, context
context options may be Dockerfile file path, may also be a link to the url git repository, when the value of providing a relative path, is interpreted as a relative path to write the file, this directory is sent to the Docker daemon the context

build:
  context: ./dir

5, dockerfile
use dockerfile files to build, you must specify the build path

build:
  context: .
  dockerfile: Dockerfile-alternate

dockerfile instruction can not be used simultaneously with the image, or Compose the uncertainty to generate the final image depending on which services directive.

6, command
using the command can override the default command is executed after the vessel started.

command: bundle exec thin -p 3000

7, CONTAINER_NAME
Compose container name format is: <project name> <service name> <number>
can customize the project name, service name, but if you want full control of the vessel name, you can use the tag to specify:

container_name: app

 

8, depends_on
when using Compose, the biggest advantage is to play a small start-up command, but the order of the general project started by the container is required, if the direct start from top to bottom of the container, because the container will inevitably depend on the issue failed to start. Such as starting an application container, the container will use the database and quit because they can not when we do not start the database container. depends_on label for container-dependent solve, the problem has started in.

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

Above YAML file defines the container will first start redis and db two services, and finally start the web service.

9、pid

pid: "host"

The PID PID mode is set to host mode, shared with the host system processes namespace. Pid will be able to use the container tag access and manipulate the namespace of the host and other containers.

10、ports

ports for mapping the label port.
Use HOST: CONTAINER format or just specified container port, port mapping host random chance.

ports:
 - "3000"
 - "8000:8000"
 - "49100:22"
 - "127.0.0.1:8001:8001"

 

When HOST: CONTAINER port mapped format, if the container is smaller than the port 60 can get incorrect results obtained, as will parse YAML xx: yy This digital format is 60-ary. It is recommended that the use of string format.

11、extra_hosts

Add tags host name, will add some records in the / etc / hosts file.

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

After you start to see inside the container hosts:

162.242.195.82  somehost
50.31.209.229   otherhost

 

12、volumes

A directory or mount an existing data volume container, can be used directly [HOST: CONTAINER] format, or use [HOST: CONTAINER: ro] format, the latter to the container, the data volume is read-only, can be effectively protection of the host file system.
Compose specified path data volume may be a relative path, use. Or .. to specify the relative directory.
Data volume format may be the following forms:

Volumes:
   // just specify a path, Docker will automatically create a data volume (the path is inside the container). 
  - / var / lib / MySQL
   // absolute path mount data volume 
  - / opt / Data: / var / lib / MySQL
   // to Compose profile centered relative path as the data volume to mount the container. 
  - ./cache:/tmp/ Cache
   // use a relative path to the user (~ directory / represents the / home / <user directory> / or / root /). 
  - ~ / configs: / etc / configs / : RO
   // existing named data volume. 
  - datavolume: / var / lib / mysql

If no path host can specify a volume_driver.

volume_driver: mydriver

13、volumes_from

Mount it from another service or data volume container:

volumes_from:
   - service_name    
     - container_name

14、dns

Custom DNS server. Can be a value, it can be a list.

dns:8.8.8.8
dns:
    - 8.8.8.8    
      - 9.9.9.9

15、dns_search

Configuring DNS search domains. Can be a value, it can be a list.

dns_search:example.com
dns_search:
    - domain1.example.com
    - domain2.example.com
16、entrypoint

There are known in Dockerfile ENTRYPOINT instruction in an instruction to specify an access point.
The access point may be defined docker-compose.yml, the cover defined in Dockerfile:

entrypoint: /code/entrypoint.sh

17、env_file

You can define a special file stored in the variable docker-compose.yml in.
If the specified configuration file docker-compose -f FILE, then the path will be used env_file profile path.
If there are conflicting instructions environment variable name, the latter shall prevail. Format is as follows:

env_file: .env

The docker-compose.yml or a plurality of:

env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env

If you have build operations in the configuration file, variable and not enter the build process.

18、cap_add

Adds the specified container core capability (capacity).
Let vessel has all the ability to specify:

cap_add:
    - ALL

19、cap_drop

Ability to remove the core specified container (capacity).
Remove NET_ADMIN capability can be specified:

cap_drop:
    - NET_ADMIN

 

Created a cgroup group name cgroups_1:

cgroup_parent: cgroups_1

 

21、devices

Specify the device mapping relationship, such as:

devices:
    - "/dev/ttyUSB1:/dev/ttyUSB0"

22、expose

Exposure to port, but does not map to the host, allowing only access to services that can be connected. Designated internal port can only be a parameter, as follows:

expose:
    - "3000"
    - "8000"

23、extends

Be extended based on other template files. For example, for webapp service defines a basic template file for the common.yml:

# common.yml
webapp:
    build: ./webapp
    environment:
        - DEBUG=false
        - SEND_EMAILS=false

Then write a new development.yml file, use the webapp service common.yml extended:

# development.yml
web:
    extends:
        file: common.yml
        service: webapp
    ports:
        - "8000:8000"
    links:
        - db
    environment:
        - DEBUG=true
db:
    image: mysql

The latter will automatically inherit the webapp service and environment variables defined in common.yml.
extends following restrictions:
A, to avoid cycle-dependent
B, and the container extends not inherit data volumes and resource links volumes_from defined in
recommendation defines only some of which may mirror and shared environment variables based on the template, the template in the extension specify application variables, links, data volume and other information

24、external_links

Links to external containers docker-compose.yml, the outer container may be non Compose management.

external_links:
    - redis_1
    - project_db_1:mysql
    - project_db_1:postgresql

25、labels

Docker adding metadata (Metadata) information container. For example, the container may be added as auxiliary information Description:

labels:
    com.startupteam.description: "webapp for a strtup team"

26、links

Links to other services in the container. Service name (alias simultaneously), or "Service Name: Alias ​​Service" (e.g. SERVICE: ALIAS), for example:

links:
    - db
    - db:database
    - redis

Services will automatically use aliases in the container / etc / hosts was created. E.g:

172.17.2.186  db
172.17.2.186  database
172.17.2.187  redis

27、log_driver

Specifies the log drive type. Currently supports three log drive type:

log_driver: "json-file"
log_driver: "syslog"
log_driver: "none"

28、log_opt

Log drive parameters. E.g:

log_driver: "syslog"log_opt: 
    syslog-address: "tcp://192.168.0.42:123"

29、net

Set network mode.

net: "bridge"
net: "none"
net: "host"

 

30、security_opt

The default template attribute specifies the container label (label) mechanism (user, role, type, level, etc.). For example, the configuration of user names and roles label name:

security_opt:
    - label:user:USER
    - label:role:ROLE

31, environment variables

Environment variables can be used to configure the behavior of Docker-Compose.
COMPOSE_PROJECT_NAME
item name to be added before the start through every container Compose, the default is the name of the current working directory.
COMPOSE_FILE
set the path docker-compose.yml template file. The default path is the current working directory.
DOCKER_HOST
set the address of Docker daemon. ///Var/run/docker.sock: use the unix default. DOCKER_TLS_VERIFY
If the setting is not empty, then interact with the Docker daemon via TLS.
DOCKER_CERT_PATH
configuration validation path (ca.pem, cert.pem and the key.pem) files required for TLS communication, the default is ~ / .docker.

Five Docker-Compose a template file example

1, write docker-compose the template file

docker-compose.yaml file as follows:

[root@topcheer docker]# cat docker-compose.yml
version: '2'
services:
  web1:
    image: nginx
    ports:
      - "6061:80"
    container_name: "web1"
  web2:
    image: nginx
    ports:
      - "6062:80"
    container_name: "web2"
[root@topcheer docker]# 

docker-compose.yaml file specifies two web services.

2, start the application

Create a webapp directory and copy the file to the docker-compose.yaml webapp directory, start the application using the docker-compose.

docker-compose up -d

 

3, service access

 

 Reference: https://www.jianshu.com/p/167b318fe9ca

Guess you like

Origin www.cnblogs.com/dalianpai/p/11951679.html