docker-compose使用

目录

Compose 简介

Compose 安装

使用样例

 Compose常用命令


Compose 简介

Compose 是用于定义和运行多容器 Docker 应用程序的工具。通过 Compose,您可以使用 YML 文件来配置应用程序需要的所有服务。然后,使用一个命令,就可以从 YML 文件配置中创建并启动所有服务。

通常来说,Compose 通过以下三个步骤来构建服务:

  • 使用 Dockerfile 定义应用程序的环境。

  • 使用 docker-compose.yml 定义构成应用程序的服务,这样它们可以在隔离环境中一起运行。

  • 最后,执行 docker-compose up 命令来启动并运行整个应用程序。

docker-compose.yml 的配置案例如下(配置参数参考下文):

实例:

version: "3.9"  # optional since v1.27.0
services:
  web:
    build: .
    ports:
      - "8000:5000"
    volumes:
      - .:/code
      - logvolume01:/var/log
    links:
      - redis
  redis:
    image: redis
volumes:
  logvolume01: {}

Compose 具有用于管理应用程序整个生命周期的命令:

  • 启动、停止和重建服务
  • 查看运行服务的状态
  • 流式传输正在运行的服务的日志输出
  • 在服务上运行一次性命令

Compose 安装

先决条件:由于docker-compose需要依赖于docker引擎,因此需要先确认当前环境已经正确安装了docker

安装步骤:

1.运行以下命令下载 Docker Compose 的当前稳定版本:

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

要安装不同版本的 Compose,请替换1.29.2 为您要使用的 Compose 版本

2.对二进制文件授予可执行权限:

 sudo chmod +x /usr/local/bin/docker-compose

如果安装后命令docker-compose失败,请检查您的路径。您还可以/usr/bin在路径中创建指向或任何其他目录的符号链接。

例如:

sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

 3.测试安装:

 docker-compose --version

docker-compose version 1.29.2, build 5becea4c

如需卸载docker-compose的话,只需要删除/usr/local/bin/下安装的docker-compose文件

 sudo rm /usr/local/bin/docker-compose

使用样例

在此,我们需要通过个 Docker Compose 来部署运行一个简单的 Python Web 应用程序

1.首先创建一个项目目录

mkdir case1
cd case1

2.然后在项目目录中创建一个名为的文件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)

在该应用中,会去访问redis(端口6379),并保存应用访问次数

3.在您的项目目录中创建另一个名为的文件requirements.txt并拷贝以下内容

flask
redis

至此,一个python应用脚本,以及运行的命令入参就创建好了。接下来,开始编写用于搭建该应用程序镜像的dockerfile


创建dockerfile

在此步骤中,需要构建 一个Docker 镜像的 Dockerfile。该镜像包含 Python 应用程序所需的所有依赖项,包括 Python 本身。

在当前目录下创建名为dockerfile的文件

创建dockerfile
vi dockerfile
拷贝以下内容至dockerfile中
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 #安装 gcc 和其他依赖项
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

 在构建好dockerfile后,就需要创建服务编排文件docker-compose.yml


在Compose中定义服务

创建docker-compose.yml,并拷贝以下内容

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"  #将主机的8000端口映射到容器的5000端口
  redis:
    image: "redis:alpine"

至此,就完成了所有文件的构建。接下来,就要通过docker-compose命令部署服务


 通过docker-compose构建python应用

在当前项目目录中执行以下指令,部署编排的服务

docker-compose up
//还可以通过 -f 参数指定docker-compose.yml,默认会从当前路径查找
//例如:docker-compose up -f ./docker-compose.yml

Creating network "case1_default" with the default driver
Creating case1_web_1   ... done
Creating case1_redis_1 ... done
Attaching to case1_web_1, case1_redis_1
redis_1  | 1:C 09 Mar 2022 02:04:00.186 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 09 Mar 2022 02:04:00.186 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 09 Mar 2022 02:04:00.186 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1  | 1:M 09 Mar 2022 02:04:00.187 * monotonic clock: POSIX clock_gettime
redis_1  | 1:M 09 Mar 2022 02:04:00.199 * Running mode=standalone, port=6379.
redis_1  | 1:M 09 Mar 2022 02:04:00.199 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1  | 1:M 09 Mar 2022 02:04:00.199 # Server initialized
redis_1  | 1:M 09 Mar 2022 02:04:00.199 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1  | 1:M 09 Mar 2022 02:04:00.200 * Ready to accept connections
web_1    |  * Serving Flask app 'app.py' (lazy loading)
web_1    |  * Environment: development
web_1    |  * Debug mode: on
web_1    |  * Running on all addresses.
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |  * Running on http://172.20.0.2:5000/ (Press CTRL+C to quit)
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 132-837-703

 docker-compose启动时会去编译下载镜像,再部署服务;可以看到我们的web服务下,有配置build项,因此,compose会从当前目录去加载dockerfile进行镜像的构建,然后再基于该构建好的镜像创建容器服务;而redis服务的话,则是直接拉取远程仓库中的镜像进行部署。


验证python应用是否正常运行

浏览器界面输入主机ip:8000,弹出以下界面则证明服务正常运行,且通讯正常;刷新界面后,统计次数会叠加


绑定挂载数据卷

在这里我们修改docker-compose.yml,添加数据卷volume配置,实现容器和主机相应目录的映射,从而能够即时修改代码,而无需重建映像。同时配置环境environment,通知flask run开发模式下运行并在更改时重新加载代码。

修改内容如下:

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"

然后,重新构建容器资源并重启服务

docker-compose up   (多次执行会重新构建资源并重启服务)

case1_redis_1 is up-to-date
Recreating case1_web_1 ... done
Attaching to case1_redis_1, case1_web_1
redis_1  | 1:C 09 Mar 2022 02:17:27.286 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 09 Mar 2022 02:17:27.286 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 09 Mar 2022 02:17:27.286 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1  | 1:M 09 Mar 2022 02:17:27.287 * monotonic clock: POSIX clock_gettime
redis_1  | 1:M 09 Mar 2022 02:17:27.288 * Running mode=standalone, port=6379.
redis_1  | 1:M 09 Mar 2022 02:17:27.288 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1  | 1:M 09 Mar 2022 02:17:27.288 # Server initialized
redis_1  | 1:M 09 Mar 2022 02:17:27.288 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1  | 1:M 09 Mar 2022 02:17:27.289 * Ready to accept connections
web_1    |  * Serving Flask app 'app.py' (lazy loading)
web_1    |  * Environment: development
web_1    |  * Debug mode: on
web_1    |  * Running on all addresses.
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |  * Running on http://172.20.0.2:5000/ (Press CTRL+C to quit)
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 674-917-153

接下来,我们修改app.py的源码,查看其是否能实时生效

#将app.py最后一行的代码替换成下列代码
return 'Hello from Docker! I have been seen {} times.\n'.format(count)

请求浏览器后,可以发现,替换的内容已经实时生效了

故在docker-compose.yml中配置volume可以实现容器和主机目录的共享,同docker中的数据卷功能一致


 Compose常用命令

#注意:以下命令都需要在具备docker-compose.yml的目录下执行,否则需要通过-f /path/docker-compose.yml指定编排文件
#下列所有命令都可以添加 --help 查看具体命令使用详情
docker-compose build   //构建或重构镜像,会读取当前路径的dockerfile重新编译生成镜像
docker-compose up      //部署服务容器资源并运行编排的服务(多次执行会重建容器资源并重启服务)
docker-compose down    //停止服务并删除容器资源
docker-compose images  //列出当前项目的所有镜像
docker-compose ps      //列出compose部署运行的所有服务
docker-compose pull    //拉取仓库中的镜像
docker-compose push    //推送本地镜像至仓库
docker-compose restart //重启服务(当前容器资源尚未删除的前提下,可以重启)
docker-compose stop    //停止服务(当前容器资源尚未删除的前提下,可以停止)
docker-compose start   //启动服务(当前容器资源尚未删除的前提下,可以启动)
docker-compose rm      //删除容器资源
docker-compose create  //创建容器资源(不会启动服务)
docker-compose run     //用于运行“一次性”或“临时”任务,且仅能启动指定的服务及其依赖
docker-compose exec    //在运行的容器中执行命令操作
docker-compose config  //校验并输出docker-compose.yml
docker-compose logs    //输出所有容器的日志,可以指定对应服务

#docker-compose up 和 docker-compose run 的区别
#docker-compose up会基于compose file 启动所有的的服务,并对外暴露端口
#docker-compose run需要指定特定的服务进行启动,比如docker-compose run web bash只会启动compose文件中的web服务和其依赖的service,并且不会对外暴露端口,以免跟docker-compose up启动的服务端口冲突(需要通过-p port:port将主机的某个端口映射到容器内的某个端口)
#docker-compose run仅用在临时启动某个服务定位问题的场景

以上指令都可以通过-f /path/docker-compose.yml指定编排服务进行操作,否则,从当前目录读取docker-compose.yml文件。例如:docker-compose -f /path/docker-compose.yml up 

docker-compose build

docker-compose build会编译构建docker-compose.yml定义的服务的镜像资源

使用说明

Build or rebuild services.

Services are built once and then tagged as `project_service`,
e.g. `composetest_db`. If you change a service's `Dockerfile` or the
contents of its build directory, you can run `docker-compose build` to rebuild it.

Usage: build [options] [--build-arg key=val...] [--] [SERVICE...]

Options:
    --build-arg key=val     Set build-time variables for services.
    --compress              Compress the build context using gzip.
    --force-rm              Always remove intermediate containers.
    -m, --memory MEM        Set memory limit for the build container.
    --no-cache              Do not use cache when building the image.
    --no-rm                 Do not remove intermediate containers after a successful build.
    --parallel              Build images in parallel.
    --progress string       Set type of progress output (auto, plain, tty).
    --pull                  Always attempt to pull a newer version of the image.
    -q, --quiet             Don't print anything to STDOUT

 样例:

[shuchang@docker01 case1]$ docker-compose build 
redis uses an image, skipping
Building web
Sending build context to Docker daemon  8.704kB
Step 1/10 : FROM python:3.7-alpine
 ---> bec8abcca4d2
Step 2/10 : WORKDIR /code
 ---> Using cache
 ---> eda8c84e4881
Step 3/10 : ENV FLASK_APP=app.py
 ---> Using cache
 ---> 052b7925b0f7
Step 4/10 : ENV FLASK_RUN_HOST=0.0.0.0
 ---> Using cache
 ---> ce342a1d4665
Step 5/10 : RUN apk add --no-cache gcc musl-dev linux-headers
 ---> Using cache
 ---> 8be4738d1774
Step 6/10 : COPY requirements.txt requirements.txt
 ---> Using cache
 ---> a8b4c057828d
Step 7/10 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 0d636b00f382
Step 8/10 : EXPOSE 5000
 ---> Using cache
 ---> 646b9e7d760c
Step 9/10 : COPY . .
 ---> 1894d317c9ae
Step 10/10 : CMD ["flask", "run"]
 ---> Running in 54c2cdcae43b
Removing intermediate container 54c2cdcae43b
 ---> a6228e94e21c
Successfully built a6228e94e21c
Successfully tagged case1_web:latest

docker-compose up

部署服务容器资源并运行编排的服务(多次执行会重建容器资源并重启服务)

Builds, (re)creates, starts, and attaches to containers for a service.

Unless they are already running, this command also starts any linked services.

The `docker-compose up` command aggregates the output of each container. When
the command exits, all containers are stopped. Running `docker-compose up -d`
starts the containers in the background and leaves them running.

If there are existing containers for a service, and the service's configuration
or image was changed after the container's creation, `docker-compose up` picks
up the changes by stopping and recreating the containers (preserving mounted
volumes). To prevent Compose from picking up changes, use the `--no-recreate`
flag.

If you want to force Compose to stop and recreate all containers, use the
`--force-recreate` flag.

Usage: up [options] [--scale SERVICE=NUM...] [--] [SERVICE...]

Options:
    -d, --detach               Detached mode: Run containers in the background,
                               print new container names. Incompatible with
                               --abort-on-container-exit.
    --no-color                 Produce monochrome output.
    --quiet-pull               Pull without printing progress information
    --no-deps                  Don't start linked services.
    --force-recreate           Recreate containers even if their configuration
                               and image haven't changed.
    --always-recreate-deps     Recreate dependent containers.
                               Incompatible with --no-recreate.
    --no-recreate              If containers already exist, don't recreate
                               them. Incompatible with --force-recreate and -V.
    --no-build                 Don't build an image, even if it's missing.
    --no-start                 Don't start the services after creating them.
    --build                    Build images before starting containers.
    --abort-on-container-exit  Stops all containers if any container was
                               stopped. Incompatible with -d.
    --attach-dependencies      Attach to dependent containers.
    -t, --timeout TIMEOUT      Use this timeout in seconds for container
                               shutdown when attached or when containers are
                               already running. (default: 10)
    -V, --renew-anon-volumes   Recreate anonymous volumes instead of retrieving
                               data from the previous containers.
    --remove-orphans           Remove containers for services not defined
                               in the Compose file.
    --exit-code-from SERVICE   Return the exit code of the selected service
                               container. Implies --abort-on-container-exit.
    --scale SERVICE=NUM        Scale SERVICE to NUM instances. Overrides the
                               `scale` setting in the Compose file if present.
    --no-log-prefix            Don't print prefix in logs.

 docker-compose down

停止服务并删除容器资源(默认移除容器资源和使用的网络,数据卷、指定网络需添加参数进行移除)

Stops containers and removes containers, networks, volumes, and images
created by `up`.

By default, the only things removed are:

- Containers for services defined in the Compose file
- Networks defined in the `networks` section of the Compose file
- The default network, if one is used

Networks and volumes defined as `external` are never removed.

Usage: down [options]

Options:
    --rmi type              Remove images. Type must be one of:
                              'all': Remove all images used by any service.
                              'local': Remove only images that don't have a
                              custom tag set by the `image` field.
    -v, --volumes           Remove named volumes declared in the `volumes`
                            section of the Compose file and anonymous volumes
                            attached to containers.
    --remove-orphans        Remove containers for services not defined in the
                            Compose file
    -t, --timeout TIMEOUT   Specify a shutdown timeout in seconds.
                            (default: 10)

 样例:

执行后,服务、容器资源以及镜像一并删除了

[shuchang@docker01 case1]$ docker-compose down
Stopping case1_web_1   ... done
Stopping case1_redis_1 ... done
Removing case1_web_1   ... done
Removing case1_redis_1 ... done
Removing network case1_default

[shuchang@docker01 case1]$ docker-compose ps
Name   Command   State   Ports
------------------------------

[shuchang@docker01 case1]$ docker-compose images
Container   Repository   Tag   Image Id   Size
----------------------------------------------

docker-compose images

罗列出已创建容器资源的镜像(只会列举出docker-compose.yml中所有服务引用的镜像)

List images used by the created containers.
Usage: images [options] [--] [SERVICE...]

Options:
    -q, --quiet  Only display IDs

样例:

[shuchang@docker01 case1]$ docker-compose images
  Container     Repository    Tag       Image Id       Size  
-------------------------------------------------------------
case1_redis_1   redis        alpine   3900abf41552   32.38 MB
case1_web_1     case1_web    latest   a6228e94e21c   189.3 MB

docker-compose ps

列举出创建的所有容器资源(注意:只会列举当前编排文件docker-compose.yml中定义的服务资源)

List containers.

Usage: ps [options] [--] [SERVICE...]

Options:
    -q, --quiet          Only display IDs
    --services           Display services
    --filter KEY=VAL     Filter services by a property
    -a, --all            Show all stopped containers (including those created by the run command)

[shuchang@docker01 case1]$ docker-compose ps
    Name                   Command               State           Ports         
-------------------------------------------------------------------------------
case1_redis_1   docker-entrypoint.sh redis ...   Up      6379/tcp              
case1_web_1     flask run                        Up      0.0.0.0:8000->5000/tcp

docker-compose pull/push

 拉取/推送镜像

[shuchang@docker01 case1]$ docker-compose pull --help
Pulls images for services defined in a Compose file, but does not start the containers.

Usage: pull [options] [--] [SERVICE...]

Options:
    --ignore-pull-failures  Pull what it can and ignores images with pull failures.
    --parallel              Deprecated, pull multiple images in parallel (enabled by default).
    --no-parallel           Disable parallel pulling.
    -q, --quiet             Pull without printing progress information
    --include-deps          Also pull services declared as dependencies

[shuchang@docker01 case1]$ docker-compose push --help
Pushes images for services.

Usage: push [options] [--] [SERVICE...]

Options:
    --ignore-push-failures  Push what it can and ignores images with push failures.

docker-compose restart/start/stop

compose启动/停止/重启服务(该操作不会删除容器资源)

[shuchang@docker01 case1]$ docker-compose restart --help

Restart running containers.

Usage: restart [options] [--] [SERVICE...]

Options:
  -t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.(default: 10)

[shuchang@docker01 case1]$ docker-compose start --help
Start existing containers.

Usage: start [SERVICE...]

[shuchang@docker01 case1]$ docker-compose stop --help
Stop running containers without removing them.

They can be started again with `docker-compose start`.

Usage: stop [options] [--] [SERVICE...]

Options:
  -t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.(default: 10)

docker-compose rm/create

compose删除/创建容器资源(只能删除已停止的服务容器资源;且创建容器资源时不会启动服务)

[shuchang@docker01 case1]$ docker-compose rm --help
Removes stopped service containers.

By default, anonymous volumes attached to containers will not be removed. You
can override this with `-v`. To list all volumes, use `docker volume ls`.

Any data which is not in a volume will be lost.

Usage: rm [options] [--] [SERVICE...]

Options:
    -f, --force   Don't ask to confirm removal
    -s, --stop    Stop the containers, if required, before removing
    -v            Remove any anonymous volumes attached to containers
    -a, --all     Deprecated - no effect.

[shuchang@docker01 case1]$ docker-compose create --help
Creates containers for a service.
This command is deprecated. Use the `up` command with `--no-start` instead.

Usage: create [options] [SERVICE...]

Options:
    --force-recreate       Recreate containers even if their configuration and
                           image haven't changed. Incompatible with --no-recreate.
    --no-recreate          If containers already exist, don't recreate them.
                           Incompatible with --force-recreate.
    --no-build             Don't build an image, even if it's missing.
    --build                Build images before creating containers.

docker-compose run

临时启动一个指定的服务及其依赖(可以通过--no-deps禁止依赖服务的启动)

Run a one-off command on a service.

For example:

    $ docker-compose run web python manage.py shell

By default, linked services will be started, unless they are already
running. If you do not want to start linked services, use
`docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.

Usage:
    run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] [--]
        SERVICE [COMMAND] [ARGS...]

Options:
    -d, --detach          Detached mode: Run container in the background, print
                          new container name.
    --name NAME           Assign a name to the container
    --entrypoint CMD      Override the entrypoint of the image.
    -e KEY=VAL            Set an environment variable (can be used multiple times)
    -l, --label KEY=VAL   Add or override a label (can be used multiple times)
    -u, --user=""         Run as specified username or uid
    --no-deps             Don't start linked services.
    --rm                  Remove container after run. Ignored in detached mode.
    -p, --publish=[]      Publish a container's port(s) to the host
    --service-ports       Run command with the service's ports enabled and mapped
                          to the host.
    --use-aliases         Use the service's network aliases in the network(s) the
                          container connects to.
    -v, --volume=[]       Bind mount a volume (default [])
    -T                    Disable pseudo-tty allocation. By default `docker-compose run`
                          allocates a TTY.
    -w, --workdir=""      Working directory inside the container

docker-compose exec

开启一个新的线程在指定的服务容器中运行指令

Execute a command in a running container

Usage: exec [options] [-e KEY=VAL...] [--] SERVICE COMMAND [ARGS...]

Options:
    -d, --detach      Detached mode: Run command in the background.
    --privileged      Give extended privileges to the process.
    -u, --user USER   Run the command as this user.
    -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                      allocates a TTY.
    --index=index     index of the container if there are multiple
                      instances of a service [default: 1]
    -e, --env KEY=VAL Set environment variables (can be used multiple times,
                      not supported in API < 1.25)
    -w, --workdir DIR Path to workdir directory for this command.

样例:

[shuchang@docker01 case1]$ docker-compose exec web cat ./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)

docker-compose config

校验并展示编排文件docker-compose.yml

Validate and view the Compose file.

Usage: config [options]

Options:
    --resolve-image-digests  Pin image tags to digests.
    --no-interpolate         Don't interpolate environment variables.
    -q, --quiet              Only validate the configuration, don't print
                             anything.
    --profiles               Print the profile names, one per line.
    --services               Print the service names, one per line.
    --volumes                Print the volume names, one per line.
    --hash="*"               Print the service config hash, one per line.
                             Set "service1,service2" for a list of specified services
                             or use the wildcard symbol to display all services.

 样例:

[shuchang@docker01 case1]$ docker-compose -f ../env_test/docker-compose.yml config
services:
  webapp:
    environment:
      image: training/webapp
      tag: latest
    image: training/webapp:latest
version: '3.9'

docker-compose logs

输出compose下所有容器的日志

View output from containers.

Usage: logs [options] [--] [SERVICE...]

Options:
    --no-color              Produce monochrome output.
    -f, --follow            Follow log output.
    -t, --timestamps        Show timestamps.
    --tail="all"            Number of lines to show from the end of the logs
                            for each container.
    --no-log-prefix         Don't print prefix in logs.

样例:

[shuchang@docker01 case1]$ docker-compose logs
Attaching to case1_redis_1, case1_web_1
redis_1  | 1:C 09 Mar 2022 06:21:26.724 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 09 Mar 2022 06:21:26.725 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 09 Mar 2022 06:21:26.725 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1  | 1:M 09 Mar 2022 06:21:26.727 * monotonic clock: POSIX clock_gettime
redis_1  | 1:M 09 Mar 2022 06:21:26.728 * Running mode=standalone, port=6379.
redis_1  | 1:M 09 Mar 2022 06:21:26.728 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1  | 1:M 09 Mar 2022 06:21:26.728 # Server initialized
redis_1  | 1:M 09 Mar 2022 06:21:26.728 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1  | 1:M 09 Mar 2022 06:21:26.728 * Ready to accept connections
web_1    |  * Serving Flask app 'app.py' (lazy loading)
web_1    |  * Environment: development
web_1    |  * Debug mode: on
web_1    |  * Running on all addresses.
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |  * Running on http://172.21.0.2:5000/ (Press CTRL+C to quit)
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 143-389-161

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值