Docker learning - compose

chaney1992 2020-11-08 23:46:13
docker learning compose


front 《Docker Study —DockerFile》 This paper introduces dockerfile Related grammar , And how to use it ; Let's learn more about docker One of the three swordsmen  Compose; Next, learn more about .

One 、docker-compose Introduce

Docker-Compose The project is Docker Official open source projects , The main use of Python To write ; Used to define and run multiple containers Docker Application tools . Use Compose, have access to YAML file To configure the application's services . And then use a command , Create and start all services from the configuration .

Compose It's a positioning “ Define and run multiple Docker Container application tools ”, Its predecessor is Fig, Currently used Compose Still compatible Fig Format template file .

Compose It contains two important concepts :

  • service (Service): An application container , It can actually contain several container instances running the same image
  • project (Project): A complete business unit consisting of a set of associated application containers , stay docker-compose.yml The document defines

Compose The default management object of is project , A set of containers in a project can be easily lifecycle managed through subcommands .

Two 、docker-compose install

Compose At present, we have fully supported Linux、Mac OS and Windows, In the installation Compose Before , You need to install Docker;( This article is mainly about window Use in )

After the installation is successful, enter :docker compose -h  

3、 ... and 、docker-compose command

After the installation is successful, take a look at compose Mainly contains commands :

 build # Build or rebuild Services
bundle # from Compose File generation Docker bundle
config # Verify and review the documentation
create # Create services
down # Stop and delete container 、 The Internet 、 Images and volumes
events # Receive real-time events from container
exec # Execute the command in the running container
help # Get command help
images # Show a list of mirrors
kill # Kill the container
logs # Check the output of the container
pause # Temporarily Out of Service
port # Public port bound to print port
ps # Show container list
pull # Pull the service image
push # Push service image
restart # Restart the service
rm # Remove the stopped container
run # Run a one-time command
scale # Set the number of containers for the service
start # Start the service
stop # Temporarily Out of Service
top # Show running processes
unpause # Cancel suspension of service
up # Create and start the container
version # Show Docker-Compose Version information 

After a general impression of the order , Next, we need to focus on the key content (docker-compose.yml) understand ; The specific parameters of each command are introduced in detail

3、 ... and 、docker-compose.yml To write

docker-compose.yml There are multiple versions : as follows

  Let's start with an official example docker-compose.yml Content :

version: "3.8"
image: redis:alpine
- "6379"
- frontend
replicas: 2
parallelism: 2
delay: 10s
condition: on-failure
image: postgres:9.4
- db-data:/var/lib/postgresql/data
- backend
max_replicas_per_node: 1
- "node.role==manager"
image: dockersamples/examplevotingapp_vote:before
- "5000:80"
- frontend
- redis
replicas: 2
parallelism: 2
condition: on-failure
image: dockersamples/examplevotingapp_result:before
- "5001:80"
- backend
- db
replicas: 1
parallelism: 2
delay: 10s
condition: on-failure
image: dockersamples/examplevotingapp_worker
- frontend
- backend
mode: replicated
replicas: 1
labels: [APP=VOTING]
condition: on-failure
delay: 10s
max_attempts: 3
window: 120s
- "node.role==manager"


According to the above example format, we can see that docker-compose.yml It mainly includes the following contents :

  • version: Specify the current docker-compose.yml Version of , Version and Docker Engine There is a corresponding relationship between versions , Such as :v3.8 Corresponding  Docker Engine 19.03.0+
  • services: service , You can define some services that the business needs , Each service can contain a service name 、 Mirror image 、 Mount the data volume 、 The network used 、 Rely on information such as services
  • networks: The network of applications , You can define the network name 、 The type of network used, etc
  • volumes: Data volume , You can define data volumes , Then mount it to different services for use

Next, let's look at the syntax and specific meaning of the relevant commands

docker-compose.yml command
Serial number Belongs to command explain
1 services build be based on Dockerfile, Appoint Dockerfile Location path ,Compose Will use it to build images automatically , Then start the service container  
2 cap_add,cap_drop Add or remove container features
3 command Override commands that are executed by default after the container is started
4 config Use “ Per service configuration ” Configuration grants access to the configuration on a per service basis . There are two ways of grammar : Short grammar 、 Long grammar
5 cgroup_parent Specify an optional parent for the container cgroup
6 container_name Container name
7 depends_on The container depends on , Used to specify other services that the service depends on
8 depoly

Specify the configuration related to the deployment and operation of the service . This is only in use docker stack deploy Takes effect when deployed to a group ,docker compose up and docker compose run This item will be ignored .

9 devices Device mapping list .
10 dns Customize DNS The server . It can be a single value or a list .
11 dns_search Customize DNS Search domain . It can be a single value or a list .
12 entrypoint Override the default entry point
13 env_file Add environment variables from file . It can be a single value or a list
14 environment Add environment variables . You can use arrays or dictionaries . Any Boolean value (true、false、yes、no) All need to be enclosed in quotation marks , To ensure that they are not YML The parser is converted to true or false.
15 expose Expose ports without publishing them to the host - They can only be accessed by linked Services . Only internal ports can be specified .
16 external_links Link to outside of this scope docker-compose.yml Even in Compose Outside the beginning of the container , Especially for containers that provide shared or public services . Specify both container name and link alias () when , please external_links Follow and legacy Similar semantics of options .
17 extra_hosts Add hostname mapping . Use with docker The same value on the client side
18 healthcheck Configure the running checks to determine if the container for the service is “ health ”
19 image Specifies the image from which to start the container . It could be a repository / Label or mirror ID
20 init Run an initialization program inside the container , To forward the signal and get the process . Set this option to true Enable this feature for the service . 
21 isolation Specify the isolation technology of the container . stay Linux On , The only supported values are default. stay Windows in , The acceptable value is default,process and hyperv.
22 labels Use Docker Tags add metadata to the container . You can use arrays or dictionaries .
23 links Link to a container in another service . Specify the service name and link alias ("SERVICE:ALIAS"), Or just specify the service name .
24 logging Logging configuration for services
25 network_mode Network mode . Use the same network name and service as the client service - Parameters docker identical .
26 networks Network to join , Reference the entry under the top-level network key .
27 pid take PID Mode set to host PID Pattern . This will open the... Between the container and the host operating system PID Address space sharing .
28 ports Exposed port  
29 restart no Is the default restart strategy , Under no circumstances will the container be restarted . When always When specified , The container always restarts . The on-failure If the exit code indicates a failure error policy, restart the container .unless-stopped Always restart the container , Unless the container stops ( Manual or other methods ).
30 secrets Use by service secrets To configure , Grant access to secrets by service .
31 security_opt Override the default label scheme for each container .
32 stop_grace_period Specify to send SIGKILL Before , If the container doesn't handle SIGTERM( Or use stop_nusignal Any stop signal specified ), How long to wait when trying to stop the container . Default 10s
33 stop_signal Set an alternate signal to stop the container . By default ,stop Use SIGTERM. Use stop_signal Setting a substitute signal can cause stop Send this signal .
34 sysctls Kernel parameters to set in the container . You can use arrays or dictionaries .
35 tmpfs Install a temporary file system in the container . It can be a single value or a list . 
36 ulimits Override the container's default ulimit. You can specify a single limit as an integer , Can also be soft / The hard limit is specified as a map .
37 userns_mode If Docker The daemons are configured with user namespaces , Then disable the user namespace for this service .
38 volumes

Mount host path or named volume , Specified as a sub option of the service . Host paths can be installed as part of the definition of a single service , And you don't have to be at the top volumes Defined in .

however , If you want to reuse volumes between multiple services , Please at the top volumes A named volume is defined in the key .

Will name volumes and services , Clusters are used with stack files .


domainname, hostname, ipc, mac_address, privileged,

read_only, shm_size, stdin_open, tty, user, working_dir

Each of them is a value , Similar to the docker run The corresponding term .
40 Volumes dirver Specifies which volume driver should be used for this volume . The default is Docker Engine Any driver configured to use , Most of the time local.
41 dirver_opts Specify a list of options as key value pairs , To the driver passed to the volume .
42 external If set to true, Specifies that the volume is in Compose Created outside .docker-compose up Don't try to create it , If it doesn't exist, it causes an error .
43 labels Use Docker Tags add metadata to the container . You can use arrays or dictionaries .
44 name Set a custom name for this volume . The name field can be used to refer to volumes that contain special characters .
45 Networks dirver Specify which driver should be used for this network .
46 dirver_opts Specify a list of options as key value pairs for drivers to pass to this network
47 attachable Use only when the driver is set to override .
48 enable_ipv6 Enable on this network IPv6 The Internet .
49 ipam Specify custom IPAM To configure
50 internal By default ,Docker A bridge network is also connected to provide external connections . If you want to create an externally isolated overlay network , You can set this option to true.
51 labels Use Docker Tags add metadata to the container . You can use arrays or dictionaries .
52 external If set to true, Specifies that the network is in Compose Created outside .docker-compose up Don't try to create it , If it doesn't exist, it causes an error .
53 name Set a custom name for this network . The name field can be used to refer to networks that contain special characters .

  Through the above, we find that ,services The relevant order in Chinese is docker Related configuration items are associated with ; Next, we're going to verify that docker-compose.yml Run the application  

Four 、 The application case

Realization effect : When based on Identity Authentication , Related sample code implementation , adopt docker-compose Start all relevant service containers , Run the program .

A、 Add... To the solution directory docker-compose.yml file :

How to add :

1、 Manually add files

2、 adopt vs Automatic addition : Select the item you want to add and right click , Pictured

Add the following :



B、 The modification is as follows :( The docker-compose.yml Relatively simple )

version: '3.4'
image: ${DOCKER_REGISTRY-}czidentityserver
context: .
dockerfile: cz.IdentityServer/Dockerfile
image: ${DOCKER_REGISTRY-}czapiorder
context: .
dockerfile: cz.Api.Order/Dockerfile
image: ${DOCKER_REGISTRY-}czapigoods
context: .
dockerfile: cz.Api.Goods/Dockerfile
image: ${DOCKER_REGISTRY-}czmvcclient
context: .
dockerfile: cz.MVCClient/Dockerfile


C、 Carry out orders docker-compose up command : After execution, you can see the following output , The compilation start is complete .

  D、 stay docker View the following in the management page :

follow-up :

First of all, the content of this article is about docker-compose The contents are introduced , The following will be true of Swarm、Machine、K8S  Do Applied Learning .

Reference resources :


  1. Miscellaneous Linux 2
  2. Self taught Linux 12. Shell advanced
  3. Linux system service control (detailed)
  4. Summary of Linux common commands (continuous update)
  5. Java7 date time API
  6. MySQL日期和时间函数汇总
  7. Common linux commands
  8. Redis set password
  9. Basic operation of MySQL
  10. Four magic functions of mybatis, don't step on the pit!
  11. Three steps to integrate activator monitoring function into your springboot
  12. Linux diff command
  13. Usage of mysqldump command in Linux
  14. JQuery uses appendto() and remove() functions to dynamically add and delete row data
  15. Research and analysis of JVM virtual machine class file
  16. Research and analysis of JVM virtual machine class file
  17. Truth and misunderstanding of Linux kernel maintainer!
  18. Official spring boot starters
  19. C connection and use of MySQL database detailed tutorial
  20. Common JVM commands and performance tuning suggestions [could not create the Java virtual machine]
  21. Spring quartz time configuration rules
  22. Technical question and answer - 2 java basic data type byte character
  23. Linux diff command
  24. Java performance optimization (2) -- jfr (Java flight recorder) tutorial
  25. JQuery table extension
  26. Oracle ASM related views (V $) and data dictionaries (x $)
  27. Learning summary of week 7 of 20145223 Java programming
  28. JDBC data type
  29. Kernel data structure migration (list and rbtree)
  30. Getting started with spring boot
  31. [Linux] classic interview questions system management backup strategy
  32. Linux file system and log analysis
  33. Chinese open source a small and full Java tool class library, powerful ah!!
  34. Linux Basics
  35. What does docker PS -aq mean
  36. Parameter validation in springboot
  37. [JavaScript] object application
  38. Introduction to Apache Maven 2 𞓜||||||||||||||||||||||||||
  39. Java common and useful troubleshooting tools (continuous improvement)
  40. Hutool -- a small and comprehensive Java tool class library, is not only a sharp tool to solve small problems in large-scale project development, but also an efficient tool in small-scale projects
  41. Maven dependency range
  42. Front end Engineer Linux command common collection
  43. [efficient coding] simple and comprehensive JDK monitoring commands. Just read this one!! A pawn in the sun
  44. Dockerfile command
  45. PNG file interpretation (2): PNG format file structure and data structure interpretation - decoding PNG data