Official docker-compose example

docker-compose is a docker orchestration tool that can download, start and automatically configure the network for the docker image with one click. The function is shown in the following example. The
official example address is to
create a new folder, and the example will be displayed in the folder.

 mkdir composetest
 cd composetest

Create a new app.py file

vim app.py

The content is as follows:

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)

Create a new requirements.txt file, the content is as follows

flask
redis

Create a new Dockerfile file with the following content:

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 new docker-compose.yml file with the following content:

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

In this way, four files needed by our project are established, and start in this directory

docker-compose up

Visit ip: 5000 address,

Insert picture description here


Insert picture description here


each visit will automatically add 1 to record the number of visits by the client.
View mirror

docker images

It is found that the three images have

Insert picture description here


been automatically downloaded. Observe the started container, as shown in the figure below, you can know that the redis and web containers have been started automatically.

Insert picture description here

Observe the network and find that a custom network of composetest_default is automatically configured.

Insert picture description here


Insert picture description here