Docker 17
撰写 | Compose

docker-compose运行 | docker-compose run

docker-compose run

Usage: run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...] Options: -d 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) -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. -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

针对服务运行一次性命令。例如,以下命令启动该web服务并bash作为其命令运行。

docker-compose run web bash

您使用的命令run从具有由服务定义的配置的新容器中启动,包括卷,链接和其他详细信息。但是,有两个重要的区别。

首先,通过的命令将run覆盖服务配置中定义的命令。例如,如果web服务配置以bash开头,则将其docker-compose run web python app.py覆盖python app.py

第二个区别是该docker-compose run命令不会创建服务配置中指定的任何端口。这可以防止端口与已打开的端口发生冲突。如果您确实想要创建服务的端口并将其映射到主机,请指定--service-ports标志:

docker-compose run --service-ports web python manage.py shell

或者,可以使用--publish-p选项,就像使用docker run

docker-compose run --publish 8080:80 -p 2022:22 -p 127.0.0.1:2021:21 web python manage.py shell

如果启动使用链接配置的服务,则该run命令首先检查链接服务是否正在运行,并在服务停止时启动该服务。一旦所有链接的服务正在运行,run执行您通过它的命令。例如,您可以运行:

docker-compose run db psql -h db -U docker

这将为链接db容器打开一个交互式 PostgreSQL shell 。

如果您不希望run命令启动链接容器,请使用--no-deps flag

docker-compose run --no-deps web python manage.py shell

fig, composition, compose, docker, orchestration, cli, run