Docker compose的安装与使用

1 docker-compose

作用,可以让我们的项目按照我们的顺序运行。它是通过 docker-compose.yml 文件来配置的,它有三个概念:

  • 项目(project),对应一个 docker-compose.yml 文件的完整配置
  • 服务(service),一个项目中可以有多个服务,定义所运行的容器所需要的镜像、资源等
  • 容器(container),一个服务中可以运行多个容器

1.1 安装

1、下载docker-compose

bash 复制代码
wget https://github.com/docker/compose/releases/download/v5.0.2/docker-compose-$(uname -s)-$(uname -m)
mv docker-compose-$(uname -s)-$(uname -m) /usr/bin/docker-compose

# 或者
curl https://github.com/docker/compose/releases/download/v5.0.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/bin/docker-compose


chmod +x /usr/bin/docker-compose

2、验证安装

bash 复制代码
[root@localhost ~]# docker-compose -v
Docker Compose version v5.0.2
[root@localhost ~]# docker-compose --version
Docker Compose version v5.0.2

1.2 命令语法

bash 复制代码
[root@localhost ~]# docker-compose --help
Usage:  docker compose [OPTIONS] COMMAND

Define and run multi-container applications with Docker

Options:
      --all-resources              Include all resources, even those not used by services
      --ansi string                Control when to print ANSI control characters ("never"|"always"|"auto")
                                   (default "auto")
      --compatibility              Run compose in backward compatibility mode
      --dry-run                    Execute command in dry run mode
      --env-file stringArray       Specify an alternate environment file
  -f, --file stringArray           Compose configuration files
      --parallel int               Control max parallelism, -1 for unlimited (default -1)
      --profile stringArray        Specify a profile to enable
      --progress string            Set type of progress output (auto, tty, plain, json, quiet)
      --project-directory string   Specify an alternate working directory
                                   (default: the path of the, first specified, Compose file)
  -p, --project-name string        Project name

Management Commands:
  bridge      Convert compose files into another model

Commands:
  attach      Attach local standard input, output, and error streams to a service's running container
  build       Build or rebuild services
  commit      Create a new image from a service container's changes
  config      Parse, resolve and render compose file in canonical format
  cp          Copy files/folders between a service container and the local filesystem
  create      Creates containers for a service
  down        Stop and remove containers, networks
  events      Receive real time events from containers
  exec        Execute a command in a running container
  export      Export a service container's filesystem as a tar archive
  images      List images used by the created containers
  kill        Force stop service containers
  logs        View output from containers
  ls          List running compose projects
  pause       Pause services
  port        Print the public port for a port binding
  ps          List containers
  publish     Publish compose application
  pull        Pull service images
  push        Push service images
  restart     Restart service containers
  rm          Removes stopped service containers
  run         Run a one-off command on a service
  scale       Scale services 
  start       Start services
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop services
  top         Display the running processes
  unpause     Unpause services
  up          Create and start containers
  version     Show the Docker Compose version information
  volumes     List volumes
  wait        Block until containers of all (or specified) services stop.
  watch       Watch build context for service and rebuild/refresh containers when files are updated

Run 'docker compose COMMAND --help' for more information on a command.

1.3 docker-compose.yml

1、编写一个docker-compose.yml文件,在文件中定义三个服务,分别是 nginx、mysql、redis 服务。

bash 复制代码
[root@localhost ~]# vim docker-compose.yml

文件内容如下:

yaml 复制代码
services:
  nginx:
    image: nginx:1.28.1
    restart: always
    container_name: nginx
    environment:
      - TZ=Asia/Shanghai
    ports:
      - 80:80
      - 443:443
    volumes:
      - /opt/nginx/log:/var/log/nginx
      - /opt/nginx/www:/usr/share/nginx/html
    depends-on:
      - mysql
      - redis
  mysql:
    image: mysql:8.4.4
    container_name: mysql
    ports:
      - 3306:3306
    command:
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_general_ci
    environment:
      MYSQL_ROOT_PASSWORD: "123456"
    volumes:
      - /opt/mysql/db:/var/lib/mysql
  redis:
    image: redis:8.4
    container_name: redis
    environment:
      - TZ=Asia/Shanghai
    ports:
      - 6379:6379
    volumes:
      - /opt/redis/data:/data
    depends_on:
      - mysql

2、运行项目,语法如下:

bash 复制代码
[root@localhost ~]# docker-compose up --help
Usage:  docker compose up [OPTIONS] [SERVICE...]

Create and start containers

Options:
      --abort-on-container-exit      Stops all containers if any container was stopped. Incompatible with -d
      --abort-on-container-failure   Stops all containers if any container exited with failure. Incompatible with -d
      --always-recreate-deps         Recreate dependent containers. Incompatible with --no-recreate.
      --attach stringArray           Restrict attaching to the specified services. Incompatible with
                                     --attach-dependencies.
      --attach-dependencies          Automatically attach to log output of dependent services
      --build                        Build images before starting containers
  -d, --detach                       Detached mode: Run containers in the background
      --dry-run                      Execute command in dry run mode
      --exit-code-from string        Return the exit code of the selected service container. Implies
                                     --abort-on-container-exit
      --force-recreate               Recreate containers even if their configuration and image haven't changed
      --menu                         Enable interactive shortcuts when running attached. Incompatible with
                                     --detach. Can also be enable/disable by setting COMPOSE_MENU environment var.
      --no-attach stringArray        Do not attach (stream logs) to the specified services
      --no-build                     Don't build an image, even if it's policy
      --no-color                     Produce monochrome output
      --no-deps                      Don't start linked services
      --no-log-prefix                Don't print prefix in logs
      --no-recreate                  If containers already exist, don't recreate them. Incompatible with
                                     --force-recreate.
      --no-start                     Don't start the services after creating them
      --pull string                  Pull image before running ("always"|"missing"|"never") (default "policy")
      --quiet-build                  Suppress the build output
      --quiet-pull                   Pull without printing progress information
      --remove-orphans               Remove containers for services not defined in the Compose file
  -V, --renew-anon-volumes           Recreate anonymous volumes instead of retrieving data from the previous containers
      --scale scale                  Scale SERVICE to NUM instances. Overrides the scale setting in the Compose
                                     file if present.
  -t, --timeout int                  Use this timeout in seconds for container shutdown when attached or when
                                     containers are already running
      --timestamps                   Show timestamps
      --wait                         Wait for services to be running|healthy. Implies detached mode.
      --wait-timeout int             Maximum duration in seconds to wait for the project to be running|healthy
  -w, --watch                        Watch source code and rebuild/refresh containers when files are updated.
  -y, --yes                          Assume "yes" as answer to all prompts and run non-interactively

使用示例:通过刚创建的 docker-compose.yml 文件来运行项目中所有服务

bash 复制代码
[root@localhost ~]# docker compose up -d
[+] up 17/17
 ✔ Image mysql:8.4.4    Pulled                                                                                      54.0s
 ✔ Network root_default Created                                                                                     0.0s
 ✔ Container redis      Created                                                                                     0.8s
 ✔ Container nginx      Created                                                                                     0.8s
 ✔ Container mysql      Created                                                                                     0.8s
[root@localhost ~]# 

1.4 常用命令

1.4.1 docker-compose up

启动并运行 docker-compose.yml 文件中所定义的所有服务。语法如下:

bash 复制代码
[root@localhost ~]# docker-compose up --help
Usage:  docker compose up [OPTIONS] [SERVICE...]

Create and start containers

Options:
      --abort-on-container-exit      Stops all containers if any container was stopped. Incompatible with -d
      --abort-on-container-failure   Stops all containers if any container exited with failure. Incompatible with -d
      --always-recreate-deps         Recreate dependent containers. Incompatible with --no-recreate.
      --attach stringArray           Restrict attaching to the specified services. Incompatible with
                                     --attach-dependencies.
      --attach-dependencies          Automatically attach to log output of dependent services
      --build                        Build images before starting containers
  -d, --detach                       Detached mode: Run containers in the background
      --dry-run                      Execute command in dry run mode
      --exit-code-from string        Return the exit code of the selected service container. Implies
                                     --abort-on-container-exit
      --force-recreate               Recreate containers even if their configuration and image haven't changed
      --menu                         Enable interactive shortcuts when running attached. Incompatible with
                                     --detach. Can also be enable/disable by setting COMPOSE_MENU environment var.
      --no-attach stringArray        Do not attach (stream logs) to the specified services
      --no-build                     Don't build an image, even if it's policy
      --no-color                     Produce monochrome output
      --no-deps                      Don't start linked services
      --no-log-prefix                Don't print prefix in logs
      --no-recreate                  If containers already exist, don't recreate them. Incompatible with
                                     --force-recreate.
      --no-start                     Don't start the services after creating them
      --pull string                  Pull image before running ("always"|"missing"|"never") (default "policy")
      --quiet-build                  Suppress the build output
      --quiet-pull                   Pull without printing progress information
      --remove-orphans               Remove containers for services not defined in the Compose file
  -V, --renew-anon-volumes           Recreate anonymous volumes instead of retrieving data from the previous containers
      --scale scale                  Scale SERVICE to NUM instances. Overrides the scale setting in the Compose
                                     file if present.
  -t, --timeout int                  Use this timeout in seconds for container shutdown when attached or when
                                     containers are already running
      --timestamps                   Show timestamps
      --wait                         Wait for services to be running|healthy. Implies detached mode.
      --wait-timeout int             Maximum duration in seconds to wait for the project to be running|healthy
  -w, --watch                        Watch source code and rebuild/refresh containers when files are updated.
  -y, --yes                          Assume "yes" as answer to all prompts and run non-interactively

使用示例:启动并运行刚创建的docker-compose.yml文件

bash 复制代码
[root@localhost ~]# docker-compose up -d
[+] up 4/4
 ✔ Network root_default Created                                                                                      0.0s
 ✔ Container mysql      Created                                                                                      0.1s
 ✔ Container nginx      Created                                                                                      0.1s
 ✔ Container redis      Created                                                                                      0.1s

1.4.2 docker-compose ls

查看运行的project

bash 复制代码
[root@localhost ~]# docker-compose ls
NAME                STATUS              CONFIG FILES
root                running(3)          /root/docker-compose.yml

[root@localhost ~]# docker compose ls
NAME                STATUS              CONFIG FILES
root                running(3)          /root/docker-compose.yml

1.4.3 docker-compose ps

查看所有运行的容器

bash 复制代码
[root@localhost ~]# docker-compose ps
NAME      IMAGE          COMMAND                  SERVICE   CREATED          STATUS          PORTS
mysql     mysql:8.4.4    "docker-entrypoint.s..."   mysql     50 seconds ago   Up 48 seconds   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp
nginx     nginx:1.28.1   "/docker-entrypoint...."   nginx     50 seconds ago   Up 48 seconds   0.0.0.0:80->80/tcp, [::]:80->80/tcp, 0.0.0.0:443->443/tcp, [::]:443->443/tcp
redis     redis:8.4      "docker-entrypoint.s..."   redis     50 seconds ago   Up 48 seconds   0.0.0.0:6379->6379/tcp, [::]:6379->6379/tcp

1.4.4 docker-compose logs

查看容器运行日志

bash 复制代码
[root@localhost ~]# docker compose logs
mysql  | 2026-02-01 07:03:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.4-1.el9 started.
mysql  | 2026-02-01 07:03:50+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
mysql  | 2026-02-01 07:03:50+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.4-1.el9 started.
mysql  | 2026-02-01 07:03:50+00:00 [Note] [Entrypoint]: Initializing database files
mysql  | 2026-02-01T07:03:50.745276Z 0 [System] [MY-015017] [Server] MySQL Server Initialization - start.
mysql  | 2026-02-01T07:03:50.746481Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.4.4) initializing of server in progress as process 81
mysql  | 2026-02-01T07:03:50.752395Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
mysql  | 2026-02-01T07:03:51.270406Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
mysql  | 2026-02-01T07:03:52.028058Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
mysql  | 2026-02-01T07:04:24.860859Z 0 [System] [MY-015018] [Server] MySQL Server Initialization - end.
mysql  | 2026-02-01 07:04:24+00:00 [Note] [Entrypoint]: Database files initialized
mysql  | 2026-02-01 07:04:24+00:00 [Note] [Entrypoint]: Starting temporary server
mysql  | 2026-02-01T07:04:24.909748Z 0 [System] [MY-015015] [Server] MySQL Server - start.
mysql  | 2026-02-01T07:04:25.218108Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.4.4) starting as process 122
mysql  | 2026-02-01T07:04:25.248001Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
mysql  | 2026-02-01T07:04:26.095589Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
mysql  | 2026-02-01T07:04:26.538040Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysql  | 2026-02-01T07:04:26.538095Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
mysql  | 2026-02-01T07:04:26.539770Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
mysql  | 2026-02-01T07:04:26.562378Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
mysql  | 2026-02-01T07:04:26.562524Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.4'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
mysql  | 2026-02-01 07:04:26+00:00 [Note] [Entrypoint]: Temporary server started.
mysql  | '/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'
mysql  | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
mysql  | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
mysql  | Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it.
mysql  | Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it.
mysql  | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
mysql  | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
mysql  | 
mysql  | 2026-02-01 07:04:28+00:00 [Note] [Entrypoint]: Stopping temporary server
mysql  | 2026-02-01T07:04:28.945953Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.4.4).
mysql  | 2026-02-01T07:04:29.813127Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.4.4)  MySQL Community Server - GPL.
mysql  | 2026-02-01T07:04:29.813158Z 0 [System] [MY-015016] [Server] MySQL Server - end.
mysql  | 2026-02-01 07:04:29+00:00 [Note] [Entrypoint]: Temporary server stopped
mysql  | 
mysql  | 2026-02-01 07:04:29+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.
mysql  | 
mysql  | 2026-02-01T07:04:29.966793Z 0 [System] [MY-015015] [Server] MySQL Server - start.
mysql  | 2026-02-01T07:04:30.207769Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.4.4) starting as process 1
mysql  | 2026-02-01T07:04:30.219577Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
mysql  | 2026-02-01T07:04:30.384983Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
mysql  | 2026-02-01T07:04:30.584095Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysql  | 2026-02-01T07:04:30.584151Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
mysql  | 2026-02-01T07:04:30.585809Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
mysql  | 2026-02-01T07:04:30.607118Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
mysql  | 2026-02-01T07:04:30.607228Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.4'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
nginx  | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
nginx  | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
nginx  | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
nginx  | 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
nginx  | 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
nginx  | /docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
nginx  | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
nginx  | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
nginx  | /docker-entrypoint.sh: Configuration complete; ready for start up
redis  | Starting Redis Server
redis  | 1:C 01 Feb 2026 15:03:50.198 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. 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:C 01 Feb 2026 15:03:50.199 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis  | 1:C 01 Feb 2026 15:03:50.199 * Redis version=8.4.0, bits=64, commit=00000000, modified=1, pid=1, just started
redis  | 1:C 01 Feb 2026 15:03:50.199 * Configuration loaded
redis  | 1:M 01 Feb 2026 15:03:50.201 * Increased maximum number of open files to 10032 (it was originally set to 1024).
redis  | 1:M 01 Feb 2026 15:03:50.201 * monotonic clock: POSIX clock_gettime
redis  | 1:M 01 Feb 2026 15:03:50.205 * Running mode=standalone, port=6379.
redis  | 1:M 01 Feb 2026 15:03:50.210 * <bf> RedisBloom version 8.4.0 (Git=unknown)
redis  | 1:M 01 Feb 2026 15:03:50.210 * <bf> Registering configuration options: [
redis  | 1:M 01 Feb 2026 15:03:50.210 * <bf> 	{ bf-error-rate       :      0.01 }
redis  | 1:M 01 Feb 2026 15:03:50.210 * <bf> 	{ bf-initial-size     :       100 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> 	{ bf-expansion-factor :         2 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> 	{ cf-bucket-size      :         2 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> 	{ cf-initial-size     :      1024 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> 	{ cf-max-iterations   :        20 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> 	{ cf-expansion-factor :         1 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> 	{ cf-max-expansions   :        32 }
redis  | 1:M 01 Feb 2026 15:03:50.211 * <bf> ]
redis  | 1:M 01 Feb 2026 15:03:50.211 * Module 'bf' loaded from /usr/local/lib/redis/modules//redisbloom.so
redis  | 1:M 01 Feb 2026 15:03:50.262 * <search> Redis version found by RedisSearch : 8.4.0 - oss
redis  | 1:M 01 Feb 2026 15:03:50.263 * <search> RediSearch version 8.4.2 (Git=9e2b676)
redis  | 1:M 01 Feb 2026 15:03:50.263 * <search> Low level api version 1 initialized successfully
redis  | 1:M 01 Feb 2026 15:03:50.265 * <search> gc: ON, prefix min length: 2, min word length to stem: 4, prefix max expansions: 200, query timeout (ms): 500, timeout policy: return, oom policy: return, cursor read size: 1000, cursor max idle (ms): 300000, max doctable size: 1000000, max number of search results:  1000000, default scorer: BM25STD, 
redis  | 1:M 01 Feb 2026 15:03:50.267 * <search> Initialized thread pools!
redis  | 1:M 01 Feb 2026 15:03:50.267 * <search> Disabled workers threadpool of size 0
redis  | 1:M 01 Feb 2026 15:03:50.269 * <search> Subscribe to config changes
redis  | 1:M 01 Feb 2026 15:03:50.270 * <search> Subscribe to cluster slot migration events
redis  | 1:M 01 Feb 2026 15:03:50.270 * <search> Enabled role change notification
redis  | 1:M 01 Feb 2026 15:03:50.270 * <search> Cluster configuration: AUTO partitions, type: 0, coordinator timeout: 0ms
redis  | 1:M 01 Feb 2026 15:03:50.271 * <search> Register write commands
redis  | 1:M 01 Feb 2026 15:03:50.271 * Module 'search' loaded from /usr/local/lib/redis/modules//redisearch.so
redis  | 1:M 01 Feb 2026 15:03:50.275 * <timeseries> RedisTimeSeries version 80400, git_sha=3520a1568ad69076d60885c70711fbdc9b448749
redis  | 1:M 01 Feb 2026 15:03:50.275 * <timeseries> Redis version found by RedisTimeSeries : 8.4.0 - oss
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> Registering configuration options: [
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> 	{ ts-compaction-policy   :              }
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> 	{ ts-num-threads         :            3 }
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> 	{ ts-retention-policy    :            0 }
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> 	{ ts-duplicate-policy    :        block }
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> 	{ ts-chunk-size-bytes    :         4096 }
redis  | 1:M 01 Feb 2026 15:03:50.276 * <timeseries> 	{ ts-encoding            :   compressed }
.......

1.4.5 docker-compose events

查看容器事件:

bash 复制代码
[root@localhost ~]# docker-compose events --help
Usage:  docker compose events [OPTIONS] [SERVICE...]

Receive real time events from containers

Options:
      --dry-run        Execute command in dry run mode
      --json           Output events as a stream of json objects
      --since string   Show all events created since timestamp
      --until string   Stream events until this timestamp
[root@localhost ~]# docker-compose events --json

如果没有发现事件,它会一直处于监听状态。

1.4.6 docker-compose pause

将服务暂停

bash 复制代码
[root@localhost ~]# docker-compose pause --help
Usage:  docker compose pause [SERVICE...]

Pause services

Options:
      --dry-run   Execute command in dry run mode
[root@localhost ~]# docker-compose pause --dry-run
[+] pause 3/3
 ✔ Container nginx Paused                                                                                            0.0s
 ✔ Container mysql Paused                                                                                            0.0s
 ✔ Container redis Paused                                                                                            0.0s
[root@localhost ~]# docker-compose pause
[+] pause 3/3
 ✔ Container mysql Paused                                                                                            0.0s
 ✔ Container nginx Paused                                                                                            0.0s
 ✔ Container redis Paused                                                                                            0.0s
 
 

然后通过 ps 查看状态

bash 复制代码
[root@localhost ~]# docker-compose ps
NAME      IMAGE          COMMAND                  SERVICE   CREATED         STATUS                  PORTS
mysql     mysql:8.4.4    "docker-entrypoint.s..."   mysql     9 minutes ago   Up 9 minutes (Paused)   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp
nginx     nginx:1.28.1   "/docker-entrypoint...."   nginx     9 minutes ago   Up 9 minutes (Paused)   0.0.0.0:80->80/tcp, [::]:80->80/tcp, 0.0.0.0:443->443/tcp, [::]:443->443/tcp
redis     redis:8.4      "docker-entrypoint.s..."   redis     9 minutes ago   Up 9 minutes (Paused)   0.0.0.0:6379->6379/tcp, [::]:6379->6379/tcp

1.4.7 docker-compose unpause

解除容器暂停状态

bash 复制代码
[root@localhost ~]# docker-compose unpause --help
Usage:  docker compose unpause [SERVICE...]

Unpause services

Options:
      --dry-run   Execute command in dry run mode
[root@localhost ~]# docker-compose unpause
[+] unpause 3/3
 ✔ Container redis Unpaused                                                                                          0.0s
 ✔ Container nginx Unpaused                                                                                          0.0s
 ✔ Container mysql Unpaused                                                                                          0.0s


[root@localhost ~]# docker-compose ps
NAME      IMAGE          COMMAND                  SERVICE   CREATED          STATUS          PORTS
mysql     mysql:8.4.4    "docker-entrypoint.s..."   mysql     11 minutes ago   Up 11 minutes   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp
nginx     nginx:1.28.1   "/docker-entrypoint...."   nginx     11 minutes ago   Up 11 minutes   0.0.0.0:80->80/tcp, [::]:80->80/tcp, 0.0.0.0:443->443/tcp, [::]:443->443/tcp
redis     redis:8.4      "docker-entrypoint.s..."   redis     11 minutes ago   Up 11 minutes   0.0.0.0:6379->6379/tcp, [::]:6379->6379/tcp

1.4.8 docker-compose stop

停止容器运行

bash 复制代码
[root@localhost ~]# docker-compose stop
[+] stop 3/3
 ✔ Container redis Stopped                                                                                           0.2s
 ✔ Container nginx Stopped                                                                                           0.2s
 ✔ Container mysql Stopped                                                                                           1.1s

然后查看容器状态:

bash 复制代码
[root@localhost ~]# docker-compose ps
NAME      IMAGE     COMMAND   SERVICE   CREATED   STATUS    PORTS
[root@localhost ~]# docker-compose ps -a
NAME      IMAGE          COMMAND                  SERVICE   CREATED          STATUS                      PORTS
mysql     mysql:8.4.4    "docker-entrypoint.s..."   mysql     13 minutes ago   Exited (0) 26 seconds ago   
nginx     nginx:1.28.1   "/docker-entrypoint...."   nginx     13 minutes ago   Exited (0) 27 seconds ago   
redis     redis:8.4      "docker-entrypoint.s..."   redis     13 minutes ago   Exited (0) 27 seconds ago   

1.4.9 docker-compose start

启动停止的容器

bash 复制代码
[root@localhost ~]# docker-compose start --help
Usage:  docker compose start [SERVICE...]

Start services

Options:
      --dry-run            Execute command in dry run mode
      --wait               Wait for services to be running|healthy. Implies detached mode.
      --wait-timeout int   Maximum duration in seconds to wait for the project to be running|healthy
[root@localhost ~]# docker-compose start
[+] start 3/3
 ✔ Container mysql Started                                                                                           0.6s
 ✔ Container nginx Started                                                                                           0.6s
 ✔ Container redis Started                                                                                           0.5s

查看容器运行状态:

bash 复制代码
[root@localhost ~]# docker-compose ps
NAME      IMAGE          COMMAND                  SERVICE   CREATED          STATUS          PORTS
mysql     mysql:8.4.4    "docker-entrypoint.s..."   mysql     14 minutes ago   Up 21 seconds   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp
nginx     nginx:1.28.1   "/docker-entrypoint...."   nginx     14 minutes ago   Up 21 seconds   0.0.0.0:80->80/tcp, [::]:80->80/tcp, 0.0.0.0:443->443/tcp, [::]:443->443/tcp
redis     redis:8.4      "docker-entrypoint.s..."   redis     14 minutes ago   Up 21 seconds   0.0.0.0:6379->6379/tcp, [::]:6379->6379/tcp

1.4.10 docker-compose exec

用于进入服务内部,语法如下:

bash 复制代码
[root@localhost ~]# docker-compose exec --help
Usage:  docker compose exec [OPTIONS] SERVICE COMMAND [ARGS...]

Execute a command in a running container

Options:
  -d, --detach            Detached mode: Run command in the background
      --dry-run           Execute command in dry run mode
  -e, --env stringArray   Set environment variables
      --index int         Index of the container if service has multiple replicas
  -T, --no-tty            Disable pseudo-TTY allocation. By default 'docker compose exec' allocates a TTY.
      --privileged        Give extended privileges to the process
  -u, --user string       Run the command as this user
  -w, --workdir string    Path to workdir directory for this command

使用示例:进入 nginx 服务中

bash 复制代码
[root@localhost ~]# docker-compose exec nginx /bin/bash
root@d446f2f23237:/# pwd
/
root@d446f2f23237:/# ls
bin   dev		   docker-entrypoint.sh  home  lib64  mnt  proc  run   srv  tmp  var
boot  docker-entrypoint.d  etc			 lib   media  opt  root  sbin  sys  usr
root@d446f2f23237:/# cd /usr/
bin/     games/   include/ lib/     lib64/   libexec/ local/   sbin/    share/   src/     
root@d446f2f23237:/# cd /usr/share/nginx/html/
root@d446f2f23237:/usr/share/nginx/html# ls
root@d446f2f23237:/usr/share/nginx/html# 

1.4.11 docker-compose down

用于停止并删除容器,语法如下:

bash 复制代码
[root@localhost ~]# docker-compose down --help
Usage:  docker compose down [OPTIONS] [SERVICES]

Stop and remove containers, networks

Options:
      --dry-run          Execute command in dry run mode
      --remove-orphans   Remove containers for services not defined in the Compose file
      --rmi string       Remove images used by services. "local" remove only images that don't have a custom tag
                         ("local"|"all")
  -t, --timeout int      Specify a shutdown timeout in seconds
  -v, --volumes          Remove named volumes declared in the "volumes" section of the Compose file and anonymous
                         volumes attached to containers

使用示例:停止并删除 docker-compose.yml 文件中所定义的所有服务。

bash 复制代码
[root@localhost ~]# docker-compose down
[+] down 4/4
 ✔ Container mysql      Removed                                                                                      1.3s
 ✔ Container redis      Removed                                                                                      0.3s
 ✔ Container nginx      Removed                                                                                      0.2s
 ✔ Network root_default Removed                                                                                      0.1s

完成后查看容器:

bash 复制代码
[root@localhost ~]# docker-compose ps -a
NAME      IMAGE     COMMAND   SERVICE   CREATED   STATUS    PORTS

1.4.12 docker-compose port

显示暴露的端口。

bash 复制代码
[root@localhost ~]# docker-compose port --help
Usage:  docker compose port [OPTIONS] SERVICE PRIVATE_PORT

Print the public port for a port binding

Options:
      --dry-run           Execute command in dry run mode
      --index int         Index of the container if service has multiple replicas
      --protocol string   tcp or udp (default "tcp")

[root@localhost ~]# docker-compose port nginx 80
0.0.0.0:80

1.5 使用案例

这个案例的功能是通过 flask 接合 redis 完成访问次统计的功能。

1.5.1 编写程序

1、创建目录

bash 复制代码
[root@localhost ~]# mkdir myapp
[root@localhost ~]# cd myapp/

2、编写应用程序

bash 复制代码
[root@localhost myapp]# vim app.py

文件内容如下:

python 复制代码
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)

3、生成程序依赖库

bash 复制代码
# 安装redis依赖库
[root@localhost myapp]# pip install redis
WARNING: pip is using lazily downloaded wheels using HTTP range requests to obtain dependency information. This experimental feature is enabled through --use-feature=fast-deps and it is not ready for production.
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting redis
  Obtaining dependency information from redis 7.1.0
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/89/f0/8956f8a86b20d7bb9d6ac0187cf4cd54d8065bc9a1a09eb8011d4d326596/redis-7.1.0-py3-none-any.whl (354 kB)
Installing collected packages: redis
Successfully installed redis-7.1.0

# 生成依赖库文件
[root@localhost myapp]# pip freeze > requirements.txt

# 查看所有的依赖库
[root@localhost myapp]# cat requirements.txt 
blinker==1.9.0
click==8.3.1
Flask==3.1.2
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.3
redis==7.1.0
Werkzeug==3.1.5

1.5.2 构建镜像

1、编写 Dockerfile

bash 复制代码
[root@localhost myapp]# vim Dockerfile

文件内容如下:

bash 复制代码
FROM python:3.14-alpine

WORKDIR /code

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 5000

CMD ["python", "app.py"]

2、编写.dockerignore

bash 复制代码
[root@localhost myapp]# vim .dockerignore

文件内容如下:

bash 复制代码
Dockerfile

目前项目结构如下:

bash 复制代码
[root@localhost myapp]# ll
total 12
-rw-r--r--. 1 root root 582 Feb  1 15:57 app.py
-rw-r--r--. 1 root root 140 Feb  1 16:10 Dockerfile
-rw-r--r--. 1 root root 122 Feb  1 16:00 requirements.txt

1.5.3 定义服务

1、编写docker-compose.yml

bash 复制代码
[root@localhost myapp]# vim docker-compose.yml

文件内容如下:

yaml 复制代码
services:
  web:
    build: .
    ports:
      - 5000:5000
    depends_on:
      - redis
  redis:
    image: redis:alpine

2、启动并运行容器

bash 复制代码
[root@localhost myapp]# docker-compose up -d
[+] Building 1.0s (11/11) FINISHED                                                                         
 => [internal] load local bake definitions                                                            0.0s
 => => reading from stdin 458B                                                                        0.0s
 => [internal] load build definition from Dockerfile                                                  0.0s
 => => transferring dockerfile: 239B                                                                  0.0s
 => [internal] load metadata for docker.io/library/python:3.14-alpine                                 0.5s
 => [internal] load .dockerignore                                                                     0.0s
 => => transferring context: 111B                                                                     0.0s
 => [1/4] FROM docker.io/library/python:3.14-alpine@sha256:31da4cb527055e4e3d7e9e006dffe9329f84ebea7  0.0s
 => => resolve docker.io/library/python:3.14-alpine@sha256:31da4cb527055e4e3d7e9e006dffe9329f84ebea7  0.0s
 => [internal] load build context                                                                     0.0s
 => => transferring context: 504B                                                                     0.0s
 => CACHED [2/4] WORKDIR /code                                                                        0.0s
 => CACHED [3/4] COPY . .                                                                             0.0s
 => CACHED [4/4] RUN pip install --no-cache-dir -r requirements.txt                                   0.0s
 => exporting to image                                                                                0.4s
 => => exporting layers                                                                               0.0s
 => => exporting manifest sha256:14115bb4b32a78f5cf05c7795ee02b749011913b8328609b0ae26aa9fa77d495     0.0s
 => => exporting config sha256:14c18ec5f9cf088d81009b11aec7e0f84f4c1a95969dddabf9a398468f5c3cbf       0.0s
 => => exporting attestation manifest sha256:fdbd71dcb2c98ea557052d328d249c74699b8fde52dd34a6210682f  0.0s
 => => exporting manifest list sha256:74de758beb8c661397b9ed7c673f4d8508e4ee4b0208f775c9b6508a68f1c8  0.0s
 => => naming to docker.io/library/myapp-web:latest                                                   0.0s
 => => unpacking to docker.io/library/myapp-web:latest                                                0.3s
 => resolving provenance for metadata file                                                            0.0s
[+] up 4/4
 ✔ Image myapp-web         Built                                                                       1.1s
 ✔ Network myapp_default   Created                                                                     0.0s
 ✔ Container myapp-redis-1 Created                                                                     0.1s
 ✔ Container myapp-web-1   Created                                                                     0.0s

3、查看运行的容器

bash 复制代码
[root@localhost myapp]# docker-compose ps
NAME            IMAGE          COMMAND                  SERVICE   CREATED              STATUS              PORTS
myapp-redis-1   redis:alpine   "docker-entrypoint.s..."   redis     About a minute ago   Up About a minute   6379/tcp
myapp-web-1     myapp-web      "python app.py"          web       About a minute ago   Up About a minute   0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp

4、访问测试

bash 复制代码
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 1 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 2 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 3 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 4 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 5 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 6 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 7 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 8 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I have been seen 9 times.

5、查看镜像

bash 复制代码
[root@localhost myapp]# docker images Use
IMAGE              ID             DISK USAGE   CONTENT SIZE   EXTRA
myapp-web:latest   b8035979844c       96.8MB           24MB    U   
redis:alpine       4eec4565e45a        130MB         33.9MB    U    

1.5.4 添加数据卷

1、修改docker-compose.yml文件

bash 复制代码
[root@localhost myapp]# vim docker-compose.yml

文件内容如下:

yaml 复制代码
services:
  web:
    build: .
    ports:
      - 5000:5000
    depends_on:
      - redis
    volumes:
      - .:/code
  redis:
    image: redis:alpine

注:新volumes密钥将主机上的项目目录(当前目录)/code安装到容器内,允许您动态修改代码,而无需重建映像。

2、重启docker-compose

bash 复制代码
[root@localhost myapp]# docker-compose up -d

3、修改宿主机中的代码

bash 复制代码
[root@localhost myapp]# vim app.py

修改内容如下:

python 复制代码
@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I am along! I have been seen {} times.\n'.format(count)

4、访问测试

bash 复制代码
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I am along! I have been seen 3 times.
[root@localhost myapp]# curl 192.168.72.169:5000
Hello World! I am along! I have been seen 4 times.
相关推荐
掘根2 小时前
【即时通讯系统】环境搭建1——gflags,spdlog
linux·运维·ubuntu
杜子不疼.2 小时前
内网监控工具翻身!Uptime Kuma+cpolar 实现远程运维自由
linux·运维·服务器
拾光Ծ2 小时前
【Linux】Ext系列文件系统(一):初识文件系统
linux·运维·服务器·硬件架构·ext文件系统
天荒地老笑话么2 小时前
Vim核心快捷键与运维实战指南
运维·vim·excel
汪碧康2 小时前
一文讲解kubernetes的gateway Api的功能、架构、部署、管理及使用
云原生·容器·架构·kubernetes·gateway·kubelet·xkube
IT19952 小时前
Linux笔记-使用systemd管理进程
linux·运维·笔记
Web极客码2 小时前
WordPress 在哪里存储网站上的图片?
运维·服务器·wordpress
大佐不会说日语~2 小时前
Docker Compose 部署 Spring Boot 应用 502 Bad Gateway 问题排查与解决
spring boot·docker·gateway·maven·故障排查
杜子不疼.2 小时前
用Claude Code构建AI内容创作工作流:从灵感到发布的自动化实践
运维·人工智能·自动化