This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Docker: Compose, Compose, Compose, Compose

We learned about Docker in the previous article, so why Compose? For example: “Compose”?

Docker Compose is an easy and efficient way to manage containers by defining and running multiple containers

Let’s take a look at the official introduction docs

What is Compose

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.

Three points were made:

  • Compose can define and run multiple containers
  • Needs to be used to the YAML configuration file
  • A single command can create and start all the services

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.

Docker Compose runs in all environments

Using Compose is basically a three-step process:

1, Define your app’s environment with a Dockerfile so it can be reproduced anywhere.

2, Define the services that make up your app in docker-compose. Yml so they can be run together in an isolated environment.

3, 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.

Three steps:

  • You need to define your Dockerfile so that it runs in any environment
  • In docker-compose. Yml/docker-document.yml/docker-document.yml So services
  • usedocker-compose binaryStart the project

To summarize the above official statement:

Docker Compose is used for batch container orchestration

If there are multiple microservices in a project (dozens or hundreds), wouldn’t it be silly to use Docker Run one at a time? In addition, it is also a very unfriendly thing for operation and maintenance. For such problems as optimization, we have Docker Compose

Is Compose available in Docker by default?

Docker has no Compose by default. Compose is an official open source project of Docker. If we use Compose, we need to install it by ourselves

How to write the YML file for Compose?

Let’s take a look at how the YML of the official document is structured:

A docker-compose.yml looks like this:

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: {}
Copy the code
  • services

The specified service

  • volumes

Specify the volume to be attached

According to the above description in the official document, we can know that Compose has two important concepts:

  • The container and related applications
  • A project is a set of associated containers

Compose the installation

Docker Compose install

1, let’s choose to install Docker Compose under Linux, run the following command to install

Sudo curl - L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname - s) - $(uname -m)" - o /usr/local/bin/docker-composeCopy the code

Once installed, we will have the docker-compose program in our Linux directory /usr/local/bin/

Add executable permissions to the docker-compose program

sudo chmod +x /usr/local/bin/docker-compose
Copy the code

3. The installation is successful. Check the version of Docker-compose and see the following information

# docker-compose versionDocker-compose version 1.29.2, build 5becea4c docker-py version: 5.0.0 CPython version: 3.7.10 OpenSSL version: OpenSSL 1.1.0L 10 Sep 2019Copy the code

Compose official case experience

Docker Compose gettingstarted

Now that we have installed Docker-compose, let’s experience the official example together. We will use it first and then study it

Prepare the environment and code

Create a compose test directory. You can run the following command in any directory

mkdir composetest
cd composetest
Copy the code

2. Write the app.py file

app.py

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)
Copy the code

The function of the py file is to register a route of /. When we access the server /, the program will read the Redis counter to determine the number of times the site has been visited

3, create a requirements.txt file for later installation

requirements.txt

flask
redis
Copy the code

Create the DockerFile file

Write Dockerfile files

Dockerfile

# 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"]
Copy the code

The meaning of the Dockerfile file is:

  • Build image based on Python: 3.7-Alpine
  • Set the working directory to /code
  • Set the FLASK_APP environment variable
  • Set the FLASK_RUN_HOST environment variable
  • runapk add --no-cache gcc musl-dev linux-headersinstruction
  • Copy filesrequirements.txtInto the container
  • Run PIP to install the components in requirements.txt
  • Expose port 5000
  • Copy. To.
  • The flask run command is executed

Define the Compose file (yML file)

docker-compose.yml

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"
Copy the code

The compose file defines two services

  • Web service, exposing port 5000
  • redis

Build and run our Compose

Before running this command, let’s take a look at what’s in our compose test directory:

Begin to build

docker-compose up

#docker-compose up
Copy the code

You can see that after the directive docker-compose up is executed, compose is also executed layer by layer, and we can see that compose is the first to establish a custom network

Creating network "composetest_default" with the default driver
Copy the code

At this point, we see that Compose is automatically creating the Redis container and the Web container for us

Creating composetest_web_1   ... done
Creating composetest_redis_1 ... done
Copy the code

Finally, we see that Compose is helping us get Redis and web up and running,

Use the curl command on the host to request the web service

curl localhost:5000
Copy the code

Sure enough, the official compose experience is no problem and nice

Using Docker Images, you’ll find composetest_Web, Python, and Redis Alpine versions, which are also something compose automatically does for us

Look at the network

docker network ls

When compose is built, it starts by creating a network for us

Is it?

A careful friend discovers why our container names are composetest_web_1, and composetest_redis_1

This is a rule in Docker Compose to identify the corresponding copy

For example, the container in compose would be named something like this:

File name _ Service name _numCopy the code

When multiple servers are clustered, the function of this num is to identify the number of replicas

Network rules

As long as multiple containers are on the same LAN, they can ping each other, communicate with each other, and access each other through domain names

For example, mysql cluster service, we can access mysql:3306, and compose will give us access to mysql:3306

We can check docker Compose above for our new custom network

docker network ls
Copy the code

# docker network inspect composetest_default. "Containers": { "25b5814cfded10e00d2e59a8e17fcba670232bce135fdabd558b7c0530d011a4": { "Name": "composetest_web_1", "EndpointID": "cb131464ea9112403f851b14a37fa5c67b023f2ce28a1e85c409e3f284f78db4", "MacAddress": "02:42: ac: 13:00:03", "IPv4Address" : "172.19.0.3/16", "IPv6Address" : "" }, "e7fedce77d3759fefde5bef84c759a5c59e033a6f48850e5930825bfc8a8444c": { "Name": "composetest_redis_1", "EndpointID": "3af891f7d52cba7ec75eb01533af1d5dae4dcd0d8bf4c55e6b342075f971be22", "MacAddress": "02:42: ac: 13:00:02", "IPv4Address" : "172.19.0.2/16", "IPv6Address" : ""}},...Copy the code

Discover that the above example, the Web service and the Redis service, are on the same network and all can communicate with each other

Stop compose

We can stop the compose by using CTRL + C

Compose can also be stopped by docker-compose down

If you stop compose, all the services involved in compose will be stopped

# docker-compose down
Stopping composetest_web_1   ... done
Stopping composetest_redis_1 ... done
Removing composetest_web_1   ... done
Removing composetest_redis_1 ... done
Removing network composetest_default
Copy the code
  • Stop composetest_web_1
  • Stop composetest_redis_1
  • Delete composetest_web_1
  • Delete composetest_redis_1
  • Remove the custom network composetest_default

summary

  • We use the Docker image to create and start the container with the docker run command
  • DockerFile can build images, that is, package services
  • Docker-compose can start projects, orchestrate multiple microservices and deploy them in the environment with one click
  • Docker networks, custom networks

References:

docker docs

Welcome to like, follow and collect

Dear friends, your support and encouragement are the motivation for me to keep sharing and improve the quality

All right, that’s it for this time

Technology is open, our mentality, should be more open. Embrace change, live in the sun, and strive to move forward.

I am nezha, welcome to like the collection, see you next time ~