Docker Compose的安装与使用
Docker-compose简介
Docker-Compose项目是Docker官方的开源项目,负责实现对Docker容器集群的快速编排。
Docker-Compose将所管理的容器分为三层,分别是工程(project),服务(service)以及容器(container)。Docker-Compose运行目录下的所有文件(docker-compose.yml,extends文件或环境变量文件等)组成一个工程,若无特殊指定工程名即为当前目录名。一个工程当中可包含多个服务,每个服务中定义了容器运行的镜像,参数,依赖。一个服务当中可包括多个容器实例,Docker-Compose并没有解决负载均衡的问题,因此需要借助其它工具实现服务发现及负载均衡。
Docker-Compose的工程配置文件默认为docker-compose.yml,可通过环境变量COMPOSE_FILE或-f参数自定义配置文件,其定义了多个有依赖关系的服务及每个服务运行的容器。
使用一个Dockerfile模板文件,可以让用户很方便的定义一个单独的应用容器。在工作中,经常会碰到需要多个容器相互配合来完成某项任务的情况。例如要实现一个Web项目,除了Web服务容器本身,往往还需要再加上后端的数据库服务容器,甚至还包括负载均衡容器等。Compose允许用户通过一个单独的docker-compose.yml模板文件(YAML 格式)来定义一组相关联的应用容器为一个项目(project)。
Docker-Compose项目由Python编写,调用Docker服务提供的API来对容器进行管理。因此,只要所操作的平台支持Docker API,就可以在其上利用Compose来进行编排管理。
Compose使用的三个步骤:
- 使用Dockerfile定义应用程序的环境。
- 使用docker-compose.yml定义构成应用程序的服务,这样它们可以在隔离环境中一起运行。
- 最后,执行docker-compose up命令来启动并运行整个应用程序。
Docker-compose的安装
安装环境:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 20.04.3 LTS
Release: 20.04
Codename: focal
直接apt命令安装:
$ sudo apt install docker-compose
... ...
$ docker-compose -v
docker-compose version 1.25.0, build unknown
简单使用
- 创建docker-compose.yml,内容如下:
version: '2'
services:
web1:
image: nginx
ports:
- "6061:80"
container_name: "nginx1"
networks:
- ng
web2:
image: nginx
ports:
- "6062:80"
container_name: "nginx2"
networks:
- ng
networks:
ng:
driver: bridge
- 启动应用
$ docker-compose up
然后就可以在浏览器访问nginx了,是不是很方便!!!
Docker-compose常用命令
Docker-compose命令格式
$ docker-compose -h
Define and run multi-container applications with Docker.
Usage:
docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
docker-compose -h|--help
Options:
-f, --file FILE Specify an alternate compose file
(default: docker-compose.yml)
-p, --project-name NAME Specify an alternate project name
(default: directory name)
--verbose Show more output
--log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
--no-ansi Do not print ANSI control characters
-v, --version Print version and exit
-H, --host HOST Daemon socket to connect to
--tls Use TLS; implied by --tlsverify
--tlscacert CA_PATH Trust certs signed only by this CA
--tlscert CLIENT_CERT_PATH Path to TLS certificate file
--tlskey TLS_KEY_PATH Path to TLS key file
--tlsverify Use TLS and verify the remote
--skip-hostname-check Don't check the daemon's hostname against the
name specified in the client certificate
--project-directory PATH Specify an alternate working directory
(default: the path of the Compose file)
--compatibility If set, Compose will attempt to convert keys
in v3 files to their non-Swarm equivalent
--env-file PATH Specify an alternate environment file
Commands:
build Build or rebuild services
bundle Generate a Docker bundle from the Compose file
config Validate and view the Compose file
create Create services
down Stop and remove containers, networks, images, and volumes
events Receive real time events from containers
exec Execute a command in a running container
help Get help on a command
images List images
kill Kill containers
logs View output from containers
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
scale Set number of containers for a service
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show the Docker-Compose version information
docker-compose up
启动服务:
$ docker-compose up -h
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.
-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.
使用如下:
$ docker-compose up -d
Starting nginx1 ... done
Starting nginx2 ... done
docker-compose ps
命令格式如下:
$ docker-compose ps -h
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)
使用如下:
$ docker-compose ps
Name Command State Ports--------------------------------------------------------------------------------------
nginx1 /docker-entrypoint.sh ngin ... Up 0.0.0.0:6061->80/tcp,:::6061->80/tcp
nginx2 /docker-entrypoint.sh ngin ... Up 0.0.0.0:6062->80/tcp,:::6062->80/tcp
docker-compose stop
命令格式如下:
$ docker-compose stop -h
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 stop
Stopping nginx2 ... done
Stopping nginx1 ... done
docker-compose down
命令格式如下:
$ docker-compose down -h
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)
使用如下:
t$ docker-compose down
Stopping nginx2 ... done
Stopping nginx1 ... done
Removing nginx2 ... done
Removing nginx1 ... done
Removing network test_ng
docker-compose logs
命令格式如下:
$ docker-compose logs -h
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.
使用如下:
$ docker-compose logs -f
... ...
docker-compose bulid
命令格式如下:
$ docker-compose build -h
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
ontents 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).
EXPERIMENTAL flag for native builder.
To enable, run with COMPOSE_DOCKER_CLI_BUILD=1)
--pull Always attempt to pull a newer version of the image.
-q, --quiet Don't print anything to STDOUT
使用如下:
$ cat docker-compose.yml
version: '2'
services:
web:
build:
dockerfile: redis.dockerfile
context: .
ports:
- "6379:6379"
container_name: "redis"
networks:
- redis
networks:
redis:
driver: bridge
$ docker-compose build
Building web
... ...
docker-compose pull
命令格式如下:
$ docker-compose pull -h
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
使用如下:
$ docker-compose pull
Pulling web1 ... done
Pulling web2 ... done
docker-compose restart
命令格式如下:
$ docker-compose restart -h
Restart running containers.
Usage: restart [options] [SERVICE...]
Options:
-t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
(default: 10)
使用如下:
$ docker-compose restart
Restarting nginx2 ... done
Restarting nginx1 ... done
docker-compose rm
命令格式如下:
$ docker-compose rm -h
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.
使用如下:
$ docker-compose rm
Going to remove nginx2, nginx1
Are you sure? [yN] y
Removing nginx2 ... done
Removing nginx1 ... done
docker-compose start
命令格式如下:
$ docker-compose start -h
Start existing containers.
Usage: start [SERVICE...]
使用如下:
$ docker-compose start
Starting web1 ... done
Starting web2 ... done
docker-compose run
命令格式如下:
$ docker-compose run -h
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 run web1
... ...
docker-compose scale
命令格式如下:
$ docker-compose scale -h
Set number of containers to run for a service.
Numbers are specified in the form `service=num` as arguments.
For example:
$ docker-compose scale web=2 worker=3
This command is deprecated. Use the up command with the `--scale` flag
instead.
Usage: scale [options] [SERVICE=NUM...]
Options:
-t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
(default: 10)
使用如下:
$ cat docker-compose.yml
version: '2'
services:
web:
image: nginx
lb:
image: dockercloud/haproxy
links:
- web
ports:
- 8080:80
volumes:
- /var/run/docker.sock:/var/run/docker.sock
$ docker-compose up --scale web=2
docker-compose pause
命令格式如下:
$ docker-compose pause -h
Pause services.
Usage: pause [SERVICE...]
使用如下:
$ docker-compose pause
Pausing nginx1 ... done
Pausing nginx2 ... done
docker-compose kill
命令格式如下:
$ docker-compose kill -h
Force stop service containers.
Usage: kill [options] [SERVICE...]
Options:
-s SIGNAL SIGNAL to send to the container.
Default signal is SIGKILL.
使用如下:
$ docker-compose kill
Killing nginx1 ... done
Killing nginx2 ... done
docker-compose config
命令格式如下:
$ docker-compose config -h
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.
--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
使用如下:
$ docker-compose config
networks:
ng:
driver: bridge
services:
web1:
container_name: nginx1
image: nginx
networks:
ng: null
ports:
- 6061:80/tcp
web2:
container_name: nginx2
image: nginx
networks:
ng: null
ports:
- 6062:80/tcp
version: '2.0'
docker-compose create
命令格式如下:
$ docker-compose create -h
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 exec
命令格式如下:
$ docker-compose exec -h
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.
使用如下:
$ docker-compose exec web1 bash
[email protected]:/#
docker-compose port
命令格式如下:
$ docker-compose port -h
Print the public port for a port binding.
Usage: port [options] SERVICE PRIVATE_PORT
Options:
--protocol=proto tcp or udp [default: tcp]
--index=index index of the container if there are multiple
instances of a service [default: 1]
使用如下:
$ docker-compose port web1 80
0.0.0.0:6061
docker-compose push
命令格式如下:
$ docker-compose push -h
Pushes images for services.
Usage: push [options] [SERVICE...]
Options:
--ignore-push-failures Push what it can and ignores images with push failures.
docker-compose uppause
命令格式如下:
$ docker-compose unpause -h
Unpause services.
Usage: unpause [SERVICE...]
使用如下:
$ docker-compose unpause
Unpausing nginx2 ... done
Unpausing nginx1 ... done
遇到的问题
- 错误:docker.credentials.errors.InitializationError: docker-credential-desktop.exe not installed or not available in PATH
执行如下命令即可:
$ rm ~/.docker/config.json
上一篇: Docker compose安装使用
下一篇: 删除目录下的子目录和文件(新)