Docker Compose
brief introduction
Problems that can be solved: DockerFile build run can only manually operate one container at a time. If 100 microservices have dependencies at the microservice level, the previous method is very cumbersome. Docker Compose can easily and efficiently manage containers. Define multiple containers to run.
Introduction to official documents
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application's services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.
Interpretation of the first paragraph:
- Define and run multiple containers
- YAML file configuration service
- What are the single command commands
Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases.
Interpretation of the second paragraph: Compose can be used in all environments
Using Compose is basically a three-step process:
- Define your app's environment with a Dockerfile so it can be reproduced anywhere.
- Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
- Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using the docker-compose binary.
Interpretation of the third paragraph:
Three steps:
- Dockerfile ensures that we can run anywhere in the project
- To define services, you need to write docker-compose.yml
- Start running project
Summary function: batch container arrangement
Self understanding
-
Compose is an official open source project of Docker and needs to be installed
-
Dockerfile lets programs run anywhere
-
YAML FILE example for Compose
version: "3.9" # optional since v1.27.0 services: web: build: . ports: - "5000:5000" volumes: - .:/code - logvolume01:/var/log links: - redis redis: image: redis volumes: logvolume01: {}
Docker compose up starting 100 services is also a one click deployment
- Compose: an important concept
- Services: containers, applications. (web,redis,mysql…)
- project: a group of associated containers. (blog, including redis, mysql and other services)
install
- From the official website, you can run the command to download
# Foreign websites download slowly curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose # Download faster in China curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
- to grant authorization
chmod +x /usr/local/bin/docker-compose
- Check the version number. If yes, the installation is successful
Quick start
Official website Get started website: https://docs.docker.com/compose/gettingstarted/
Quick start detailed steps
Build a simple python web application on Docker Compose. The application uses the Flask framework and maintains an account in Redis
The counter is used to record the number of times the Web application is accessed.
- preparation
yum install python-pip # pip is a python package management tool yum -y install epel-release # Execute when an error is reported
- Create a directory for the project
[root@cVzhanshi home]# mkdir composetest [root@cVzhanshi home]# cd composetest
- Create a file named app.py in the project directory, with the following contents: (app)
import time import redis from flask import Flask app = Flask(__name__) cache = redis.Redis(host='redis', port=6379) def get_hit_count(): retries = 5 while True: try: return cache.incr('hits') except redis.exceptions.ConnectionError as exc: if retries == 0: raise exc retries -= 1 time.sleep(0.5) @app.route('/') def hello(): count = get_hit_count() return 'Hello World! I have been seen {} times.\n'.format(count) if __name__ == "__main__": app.run(host="0.0.0.0",debug=True)
In this example, redis is the host name of the redis container on the application network. We use the default port 6379 of redis.
- Create another file named requirements.txt in the project directory, as follows:
flask redis
- In the project directory, create a file named Dockerfile: (the application is packaged as an image)
FROM python:3.6-alpine ADD . /code WORKDIR /code RUN pip install -r requirements.txt CMD ["python","app.py"] # This tells Docker: # Build the image from the python 3.6 image. # Add the current directory to the path in the / code image # Set the working directory to / code. # Install Python dependencies. # Set the default command of the container to python app. py. # Content of official website # syntax=docker/dockerfile:1 FROM python:3.7-alpine WORKDIR /code ENV FLASK_APP=app.py ENV FLASK_RUN_HOST=0.0.0.0 RUN apk add --no-cache gcc musl-dev linux-headers COPY requirements.txt requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 COPY . . CMD ["flask", "run"]
- Create a file named docker-compose.yml in the project directory: (define the entire service, required environment, web, redis, and complete online services)
version: "3.8" services: web: build: . ports: - "5000:5000" volumes: - .:/code redis: image: "redis:alpine"
- Run the command docker compose up in the project directory
technological process:
1. Create network
2. Execute docker-compose.yml
3. Start service
Automatic default rule
1. File name composetest
2. Service
version: "3.8" services: web: build: . ports: - "5000:5000" volumes: - .:/code redis: image: "redis:alpine"
docker images
[root@cVzhanshi ~]# docker service ls Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.
Default service name: file name service name _num
In the future, the service may be a cluster and deployed on multiple servers, so _numis the number of replicas
3. Network rules
10 services are composed = > Project (Compose will automatically put the services in the project under the same network, which can be accessed through domain name and service name)
- Check the network details of compose and find that different services are under the same network, so they can be accessed through domain name and service name
[root@cVzhanshi composetest]# docker network inspect composetest_default
Stop the compose service
- ctrl + c
- docker-compose down
docker-compose
Previously, a single docker run started the container
Docker compose. Write yaml configuration files through docker compose, and you can start and stop with one click of compose
Docker summary
1. Docker image. Run = > container
2. DockerFile build image (service packaging)
3. Docker compose startup project (orchestration, multiple microservices / environments)
4. Docker network!
Yaml rule
Official documents: https://docs.docker.com/compose/compose-file/compose-file-v3/
# 3rd floor # first floor version: '' # edition # The second time services: # service Service 1: web # Service configuration images build network ...... Service 2: redis ...... # Layer 3 other configuration network / volume, global rules volumes: networks: configs:
Briefly introduce several:
- Dependencies_on dependencies
version: "3.9"services: web: build: . depends_on: # web depends on db and redis, so the startup sequence is db and redis first, and then web - db - redis redis: Image: redis db: Image: Postgres
Actual combat: use Compose to deploy WP blog with one click
- create folder
[root@cVzhanshi home]# mkdir my_wordpress [root@cVzhanshi home]# cd my_wordpress/
- Write the docker-compose.yml configuration file as follows:
version: "3.8" services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest volumes: - wordpress_data:/var/www/html ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: db_data: {} wordpress_data: {}
- One touch start
# One click Start foreground start docker-compose up # Background enlightenment docker-compose up -d
Actual combat: write your own timer and pack it
- Create a springboot project and tick the web and redis dependencies
- Write configuration file
server: port: 8080 spring: redis: host: redis
- Write business controller
@RestController public class TestController { @Autowired StringRedisTemplate redisTemplate; @GetMapping("/hello") public String hello(){ Long views = redisTemplate.opsForValue().increment("views"); return "hello cvzhanshi,thank you views:" + views; } }
- Write Dockerfile
FROM java:8 COPY *.jar /app.jar CMD ["--server.port=8080"] EXPOSE 8080 ENTRYPOINT ["java","-jar","/app.jar"]
- Write docker-compose.yml
version: '3.8' services: cvzhanshiapp: build: . image: cvzhanshiapp depends_on: - redis ports: - "8089:8089" redis: image: "redis:alpine"
- Upload to server
- The docker compose up command starts orchestration
- test