Docker Quick Start -- docker-compose

Source: Internet
Author: User
Tags sigint signal syslog
Docker Quick Start-docker-Compose 1. Introduction to docker-Compose 1. docker compose Introduction to docker-compose

The docker-Compose project is an official open-source project of docker. It is responsible for fast orchestration of docker container clusters.
Docker-Compose divides the managed containers into three layers: Project, service, and container ). All the files under the docker-Compose running directory (docker-compose.yml, extends file, environment variable file, etc.) form a project, and the current directory name is the name if no special project name is specified. A project can contain multiple services. Each service defines the image, docker compose volumes parameters, and dependencies of container operations. A service can contain multiple container instances. docker-Compose does not solve the load balancing problem. Therefore, you need to use other tools to achieve service discovery and load balancing.
The docker-Compose Project Profile defaults to a docker-compose.yml, which can be customized through the Environment Variable compose_file or the-F parameter, it defines multiple dependent services and containers running each service.
Using a dockerfile template file allows you to easily define a separate application container. At work, you may often encounter situations where multiple containers need to work together to complete a task. For example, docker compose command to implement a web project, in addition to the Web Service container itself, docker compose up you often need to add backend database service containers, docker compose build install docker compose or even load balancing containers.
Compose allows users to define a group of associated application containers as a project through a separate docker-compose.yml template file (in yaml format ).
The docker-Compose project is written in Python and uses the APIS provided by the docker Service to manage containers. Therefore, as long as the operating platform supports docker APIs, you can use compose for orchestration management.

2. Install docker-compose 

Installation Method 1:
Download docker-compose:

sudo curl -L https://github.com/docker/compose/releases/download/1.23.0-rc3/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose

Install docker-compose:
sudo chmod +x /usr/local/bin/docker-compose
View version:
docker-compose version
Installation Method 2:
Install Pip

yum -y install epel-releaseyum -y install python-pip

Confirm version
pip --version
Update Pip
pip install --upgrade pip
Install docker-compose
pip install docker-compose
View version
docker-compose version
Install the completion tool:
To facilitate command input, you can also install the docker completion prompt tool to help you quickly enter the command:
Install
yum install bash-completion
Download the docker-Compose script

curl -L https://raw.githubusercontent.com/docker/compose/$(docker-compose version --short)/contrib/completion/bash/docker-compose > /etc/bash_completion.d/docker-compose
3. Uninstall docker-compose

If the Binary Package is installed, delete the binary file:
sudo rm /usr/local/bin/docker-compose
If Python Pip is installed, run the following command to delete it:
sudo pip uninstall docker-compose

Ii. Common docker-Compose commands 1. docker-Compose Command Format
docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]

Command Options:
-F,-file specifies the compose template file, which is a docker-compose.yml by default and can be specified multiple times.
-P,-project-name specifies the project name. By default, the directory name is used as the project name.
-X-Network-Driver: Use docker's pluggable network backend features (docker version 1.9 + is required)
-X-Network-driver Driver specifies the network backend driver. The default value is bridge (docker 1.9 + is required)
-Verbose outputs more debugging information
-V and-version: print the version and exit.

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

Options include:
-D. Run the service container in the background
-No-color does not use colors to differentiate the control output of different services.
-No-deps does not start the container linked to the service
-Force-recreate: force the container to be re-created. It cannot be used together with-no-recreate.
-No-recreate: if the container already exists, it is not re-created and cannot be used with-force-recreate
-No-build does not automatically build the missing Service Image
-Build: Build a service image before starting the container
-Abort-on-container-Exit: stops all containers. If any container is stopped, it cannot be used together with-D.
-T,-Timeout timeout when the container is stopped (10 seconds by default)
-Remove-orphans: delete containers not defined in the compose file in the service.
-Scale service = num: set the number of containers running the service, which will overwrite the parameters specified by scale in compose.
docker-compose up
Start all services
docker-compose up -d
Start all services in the background
-F specifies the compose template file to use, which is a docker-compose.yml by default and can be specified multiple times.
docker-compose -f docker-compose.yml up -d

3. docker-Compose PS

docker-compose ps [options] [SERVICE...]
docker-compose ps
List all current containers in the project

4. docker-Compose stop

docker-compose stop [options] [SERVICE...]
Options include:
-T,-Timeout timeout when the container is stopped (10 seconds by default)
docker-compose stop
Stop a running container and start it again through docker-Compose start.

5. docker-Compose-H

docker-compose -h
View help

6. docker-Compose down

docker-compose down [options]
Stop and delete containers, networks, volumes, and images.
Options include:
-RMI type: delete an image. The image type must be: All. delete all the images defined in the compose file. Local: delete an image with an empty image name.
-V,-volumes, delete the volumes that have been defined and anonymously attached to the container in the compose File
-Remove-orphans: delete containers not defined in compose in the service.
docker-compose down
Disable removing all containers and network-related

7. docker-Compose logs

docker-compose logs [options] [SERVICE...]
View the output of the Service container. By default, docker-Compose uses different colors for different service outputs. You can use-no-color to disable the color.
docker-compose logs
View service container output

8. docker-Compose build

docker-compose build [options] [--build-arg key=val...] [SERVICE...]
Build (re-build) Service containers in the project.
Options include:
-Compress uses gzip compression to build the upper and lower environments.
-Force-RM: delete temporary containers during build
-No-Cache: no cache is used during image building
-Pull always tries to pull the image of the updated version.
-M,-memory mem: Set the memory size for the built container
-Build-Arg key = VAL: set the build-time variable for the service.
Once a service container is built, a tag name is added. You can run docker-Compose build in the project directory at any time to re-build the service.

9. docker-Compose pull

docker-compose pull [options] [SERVICE...]
Pull the image on which the service depends.
Options include:
-Ignore-pull-failures: Ignore errors during image pulling
-Parallel: multiple images are pulled at the same time.
-Quiet: No progress information is printed during image pulling.
docker-compose pull
Pull the image on which the service depends

10. docker-Compose restart

docker-compose restart [options] [SERVICE...]
Restart the services in the project.
Options include:
-T,-Timeout timeout, specifies the timeout for stopping the container before restart (default value: 10 seconds)
docker-compose restart
Restart services in the project

11. docker-Compose RM

docker-compose rm [options] [SERVICE...]
Delete all (stopped) Service containers.
Options include:
-F,-force, forced direct deletion, including non-stop containers
-V: Delete the data volume attached to the container.
docker-compose rm
Delete all (stopped) Service containers. We recommend that you first run the docker-Compose Stop command to stop the container.

12. docker-Compose start

docker-compose start [SERVICE...]
docker-compose start
Start an existing service container.

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
Run a ping command on the specified container.

14. docker-Compose Scale

docker-compose scale web=3 db=2
Sets the number of containers running the specified service. Set the quantity through the service = num Parameter

15. docker-Compose pause

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

16. docker-Compose kill

docker-compose kill [options] [SERVICE...]
The service container is forced to stop by sending the sigkill signal .?
You can use the-S parameter to specify the signal to be sent. For example, you can use the following command to send a SIGINT signal:
docker-compose kill -s SIGINT

17. dokcer-Compose config

docker-compose config [options]
Verify and view the compose file configuration.
Options include:
-Resolve-image-digests: Mark image labels as abstract
-Q,-quiet only verifies the configuration and does not output it. When the configuration is correct, NO content is output. When the file configuration is incorrect, an error message is output.
-Services: print the service name, one row
-Volumes: print the volume name, one row

18. docker-Compose create

docker-compose create [options] [SERVICE...]
Create a container for the service.
Options include:
-Force-recreate: re-create the container. The no-recreate parameter is not compatible even if the configuration and image are not changed.
-No-recreate: if the container already exists, it does not need to be re-created. It is not compatible with the-force-recreate parameter.
-No-Build: do not create an image, even if it is missing
-Build: The image is generated before the container is created.

19. docker-Compose Exec

docker-compose exec [options] SERVICE COMMAND [ARGS...]
Options include:
-D Separation mode: run commands in the background.
-Privileged: Obtain the privilege.
-User User: Specifies the user to run.
-T disables tty allocation. By default, tty is allocated to docker-Compose exec.
-Index = index: when a service has multiple containers, you can use this parameter to log on to any service under the service. For example: docker-Compose Exec-Index = 1 web/bin/bash. The web service contains multiple containers.

20. docker-Compose Port

docker-compose port [options] SERVICE PRIVATE_PORT
Displays the public ports mapped to a container port.
Options include:
-Protocol = proto: Specifies the port protocol, TCP (default), or UDP
-Index = index. If you agree that the service has multiple containers, specify the serial number of the command object container (1 by default)

21. docker-Compose push

docker-compose push [options] [SERVICE...]
The image of the push service.
Options include:
-Ignore-push-failures: Ignore errors during image push

22. docker-Compose stop

docker-compose stop [options] [SERVICE...]
Displays the running processes of each container.

23. docker-Compose unpause

docker-compose unpause [SERVICE...]
Resume the service in the paused status.

24. docker-Compose version

docker-compose version
Print version information.

Iii. docker-Compose template file 1. Introduction to docker-Compose Template File

Compose allows users to define a group of associated application containers as a project through a docker-compose.yml template file (in yaml format ).
The compose template file is a yaml file that defines services, networks, and volumes. The default path to the compose template file is the docker-compose.yml under the current directory, and you can use. yml or. yaml as the file extension.
The docker-Compose standard template file should contain three parts: version, services, and networks. The most important part is services and networks.

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

Currently, compose has three versions: Version 1, version 2, and version 3. Compose distinguishes version 1 from Version 2 (compose 1.6.0 +, docker engine 1.10.0 + ). Version 2 supports more commands. Version 1 will be discarded in the future.

2. Image

Image is the image name or ID of the specified service. If the image does not exist locally, compose will try to pull the image.

services:     web:         image: hello-world
3. Build

In addition to the specified image, the service can also execute the build task when starting with up based on a dockerfile. The build tag is build, and the path of the folder where dockerfile is located can be specified. Compose automatically creates an image using dockerfile and then starts the service container using the image.
build: /path/to/build/dir
It can also be a relative path and can be read to the dockerfile as long as the context is determined.
build: ./dir
Set the context root directory and specify the dockerfile Based on the directory.

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

Build is a directory. to specify the dockerfile, you must use the dockerfile tag in the Child tag of the build tag.
If both the image and build labels are specified, compose will build the image and name the image as the name specified by the image value.

4. Context

The context option can be the file path of dockerfile or the URL linked to the GIT repository. When the provided value is a relative path, it is parsed as the path relative to the written file, this directory is also the context that is sent to the docker daemon.

build:  context: ./dir
5. dockerfile

Use the dockerfile to build the file. You must specify the build path.

build:  context: .  dockerfile: Dockerfile-alternate

The dockerfile command cannot be used together with the image; otherwise, compose will not determine which command to generate the final service image.

6. Command

Use command to overwrite the commands executed by default after the container is started.
command: bundle exec thin -p 3000

7. container_name

The container name format of compose is: <Project Name> <service name> <No.>
You can customize the project name and service name. to fully control the container name, you can use the label to specify:
container_name: app

8. depends_on

When using compose, the biggest benefit is to run fewer startup commands, but generally there are requirements for the order in which the project container starts. If the container is started directly from top to bottom, startup will inevitably fail due to container dependency issues. For example, if the application container is started when the database container is not started, the application container will exit because the database cannot be found. The depends_on label is used to solve the dependency and startup sequence of containers.

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

The containers defined in the preceding yaml file start redis and DB before starting the web service.

9. PID

pid: "host"
Set PID mode to host PID mode and share the process namespace with the host system. The container uses the PID label to access and manipulate the namespaces of other containers and hosts.

10. Ports

Ports labels used to map ports.
Use the Host: container format or only specify the container port. The host will map the port randomly.

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

When the host: iner format is used to map ports, if the container port used is smaller than 60, an error may be returned because yaml will parse XX: YY is in the 60-digit format. Therefore, we recommend that you use the string format.

11. extra_hosts

Add the host name tag. Some records are added to the/etc/hosts file.

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

View the internal hosts of the container after startup:

162.242.195.82  somehost50.31.209.229   otherhost
12. Volumes

To mount a directory or an existing data volume container, you can directly use the [host: container] format or the [host: container: RO] format. For the latter, the data volume is read-only and can effectively protect the file system of the host.
The data volume of compose can be a relative path, and the relative directory can be specified using... or.
The data volume format can be as follows:

Volumes: // only specifies a path. docker will automatically create a data volume (this path is inside the container ). -/Var/lib/MySQL // use the absolute path to mount the data volume-/opt/data: /var/lib/MySQL // The relative path centered on the compose configuration file is mounted to the container as a data volume. -./Cache:/tmp/cache // use the user's relative path (~ /Indicates/home/<user directory>/or/root /). -~ /Configs:/etc/configs/: RO // an existing named data volume. -Datavolume:/var/lib/MySQL

If you do not use the host machine path, you can specify a volume_driver.
volume_driver: mydriver

13. volumes_from

Mount a data volume from another service or container:

volumes_from:   - service_name         - container_name
14. DNS

Custom DNS server. It can be a value or a list.

dns:8.8.8.8dns:    - 8.8.8.8          - 9.9.9.9
15. dns_search

Configure the DNS search domain. It can be a value or a list.

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

In dockerfile, there is an instruction called entrypoint, which is used to specify the access point.
You can define access points in the docker-compose.yml to override definitions in dockerfile:
entrypoint: /code/entrypoint.sh

17. env_file

In a docker-compose.yml, you can define a file that specifically stores variables.
If you specify the configuration file through docker-Compose-F file, the path in env_file uses the configuration file path.
If the variable name conflicts with the Environment command, the latter prevails. The format is as follows:
env_file: .env
Or set multiple according to the docker-compose.yml:

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

If there is a build operation in the configuration file, the variable does not enter the build process.

18. cap_add

Adds the capacity of the specified container ).
To make the container have all the capabilities, you can specify:

cap_add:    - ALL
19. cap_drop

Removes the kernel capacity of the specified container ).
To remove the net_admin capability, you can specify:

cap_drop:    - NET_ADMIN
20. cgroup_parent

A cgroup group named cgroups_1 is created:
cgroup_parent: cgroups_1

21. Devices

Specify the device ing relationship, for example:

devices:    - "/dev/ttyUSB1:/dev/ttyUSB0"
22. Expose

Expose the port, but do not map it to the host. Only accessible services can be connected. You can only specify the internal port as the parameter, as shown below:

expose:    - "3000"    - "8000"
23. extends

Extension Based on other template files. For example, the webapp service defines a basic template file as common. yml:

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

Compile a new development. yml file and use the webapp service in common. yml for extension:

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

The latter automatically inherits the webapp service and environment variable definitions in common. yml.
Extends has the following restrictions:
A. Avoid circular dependency
B. extends does not inherit the containers and data volume resources defined in links and volumes_from.
We recommend that you define only some images and environment variables that can be shared in the basic template, and specify the Application variables, links, data volumes, and other information in the extended template.

24. external_links

A container linked to the outside of the docker-compose.yml can be an external container that is not managed by compose.

external_links:    - redis_1    - project_db_1:mysql    - project_db_1:postgresql
25. Labels

Add docker metadata (metadata) Information to the container. For example, you can add auxiliary instructions for containers:

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

Link to containers in other services. Use a service name (also used as an alias) or "service name: Service alias" (for example, service: alias), for example:

links:    - db    - db:database    - redis

The alias is automatically created in/etc/hosts in the service container. For example:

172.17.2.186  db172.17.2.186  database172.17.2.187  redis
27. log_driver

Specify the log driver type. Currently, three log driver types are supported:

log_driver: "json-file"log_driver: "syslog"log_driver: "none"
28. log_opt

Log driver parameters. For example:

log_driver: "syslog"log_opt:     syslog-address: "tcp://192.168.0.42:123"
29. net

Set the network mode.

net: "bridge"net: "none"net: "host"
30. security_opt

Specify the default attributes (user, role, type, level, etc.) of the container template label mechanism ). For example, configure the user name and role name of the tag:

security_opt:    - label:user:USER    - label:role:ROLE
31. Environment Variables

Environment variables can be used to configure docker-Compose behavior.
Compose_project_name
Set the name of the project added before each container started using compose. The default value is the name of the current working directory.
Compose_file
Set the path to the docker-compose.yml template file. The default path is the current working directory.
Docker_host
Set the docker daemon address. UNIX: // var/run/docker. Sock is used by default. Docker_tls_verify
If the setting is not blank, it interacts with docker daemon through TLS.
Docker_cert_path
The path of the authentication (ca. Pem, cert. Pem, and key. pem) file required for TLS communication configuration. The default path is ?~ /. Docker ?.

4. docker-Compose template file Example 1. Write the docker-Compose Template File

The docker-compose.yaml file is as follows:

version: ‘2‘services:  web1:    image: nginx    ports:       - "8080:80"    container_name: "web1"    networks:      - dev  web2:    image: nginx    ports:       - "8081:80"    container_name: "web2"    networks:      - dev      - pro  web3:    image: nginx    ports:       - "8082:80"    container_name: "web3"    networks:      - pronetworks:  dev:    driver: bridge  pro:    driver: bridge#volumes:

The docker-compose.yaml file specifies three web services.

2. Start the application

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

3. Service Access

Access web1, web2, and web3 services through a browser:
Http: // 127.0.0.1: 6061
Http: // 127.0.0.1: 6062
Http: // 127.0.0.1: 6063

Docker Quick Start -- docker-compose

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.