Docker Compose介紹
Docker Compose是Docker編排服務的最後一塊,前面提到的Machine可以讓用戶在其它平臺快速安裝Docker,Swarm可以讓Docker容器在集羣中高效運轉,而Compose可以讓用戶在集羣中部署分佈式應用
安裝Docker Compose的三種方法:
官方文檔:https://docs.docker.com/compose/install/#install-compose
1、直接下載編譯好的二進制文件,即可使用,命令如下:
sudo curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose
卸載:
sudo rm /usr/local/bin/docker-compose
2、pip安裝
sudo pip install docker-compose
卸載:
pip uninstall docker-compose
3、直接運行在docker容器中,這種方式適合雲計算場景
$ sudo curl -L --fail https://github.com/docker/compose/releases/download/1.21.2/run.sh -o /usr/local/bin/docker-compose $ sudo chmod +x /usr/local/bin/docker-compose
Compose選項:
-f, --file FILE:指定使用的Compose文件,默認爲docker-compose.yml,可以多次指定 -p, --project-name NAME:指定項目名稱,默認將使用所在目錄名稱作爲項目名 --x-networking:使用docker的可拔插網絡後端特性,需要1.9及以上版本 --x-network-driver DRIVER:指定網絡後端的驅動,默認爲bridge,需要1.9及以上版本 --verbose:輸出更多調試信息 -v, --version打印版本並退出
Compose命令
build:構建項目中的服務容器
Usage: build [options] [--build-arg key=val...] [SERVICE...] Options: --compress Compress the build context using gzip. --force-rm Always remove intermediate containers. 刪除構建過程中的臨時容器 --no-cache Do not use cache when building the image. 構建鏡像過程中不使用緩存 --pull Always attempt to pull a newer version of the image. 始終嘗試通過拉取操作來獲取更新版本的鏡像 -m, --memory MEM Sets memory limit for the build container. --build-arg key=val Set build-time variables for services.
構建項目中的服務容器,服務容器一旦構建後,將會帶上一個標記名,例如對於web項目中的一個db容器,可能是web_db。可以隨時在項目目錄下運行docker-compose build來重新構建服務
config:驗證和查看compose文件,
Usage: config [options] Options: --resolve-image-digests Pin image tags to digests. -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.
-q, --quiet:只驗證不輸出,當配置正確時,不輸出任何信息,當配置錯誤時,輸出錯誤信息
--services:打印服務名,一行一個
例如:
[root@OPS01-LINTEST02 composetest]# docker-compose config services: redis: image: redis:alpine web: build: context: /opt/composetest ports: - 5000:5000/tcp volumes: - /opt/composetest:/code:rw version: '3.0' [root@OPS01-LINTEST02 composetest]# docker-compose config -q [root@OPS01-LINTEST02 composetest]# docker-compose config --services web redis
create:爲服務創建容器,只是單純的create,還需要使用start啓動compose
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.
down:停止和刪除容器、網絡、卷、鏡像,這些內容是通過docker-compose up命令創建的. 默認值刪除 容器 網絡,可以通過指定 rmi volumes參數刪除鏡像和卷
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)
例如:
[root@OPS01-LINTEST02 composetest]# docker-compose down Stopping composetest_web_1 ... done Stopping composetest_redis_1 ... done Removing composetest_web_1 ... done Removing composetest_redis_1 ... done Removing network composetest_default [root@OPS01-LINTEST02 composetest]# docker images # docker images REPOSITORY TAG IMAGE ID CREATED SIZE composetest_web latest 531a43261c49 3 hours ago 92.7MB
可以看到容器被刪除了,但是鏡像還在。
[root@OPS01-LINTEST02 composetest]# docker-compose down --rmi all Stopping composetest_web_1 ... done Stopping composetest_redis_1 ... done Removing composetest_web_1 ... done Removing composetest_redis_1 ... done Removing network composetest_default Removing image composetest_web Removing image redis:alpine
可以看到鏡像也被刪除了
event: 輸出docker-compose 事件的日誌,當執行docker-compose命令操作時,docker-compose event命令就會監控日誌:
Usage: events [options] [SERVICE...] Options: --json Output events as a stream of json objects
exec:和docker exec命令功能相同,可以通過service name登陸到容器中
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. 禁用分配TTY. By default `docker-compose exec` 分配一個TTY. --index=index index of the container if there are multiple instances of a service [default: 1] 當一個服務擁有多個容器時,可通過該參數登陸到該服務下的任何服務,例如:docker-compose exec --index=1 web /bin/bash ,web服務中包含多個容器 -e, --env KEY=VAL Set environment variables (can be used multiple times, not supported in API < 1.25)
例如:
[root@OPS01-LINTEST02 composetest]# docker-compose config --services web redis [root@OPS01-LINTEST02 composetest]# docker-compose exec web sh /code # ls Dockerfile docker-compose.yml app.py requirements.txt
kill:通過發送 SIGKILL 信號來強制停止服務容器。支持通過參數來指定發送的信號
Usage: kill [options] [SERVICE...] Options: -s SIGNAL SIGNAL to send to the container. Default signal is SIGKILL.
例如:停止web服務
# docker-compose kill -s SIGKILL web Killing composetest_web_1 ... done # docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 98ddb468d67a composetest_web "python app.py" 7 minutes ago Exited (137) 4 seconds ago composetest_web_1
logs:顯示日誌輸出.
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 Attaching to composetest_web_1, composetest_redis_1 web_1 | * Serving Flask app "app" (lazy loading) web_1 | * Environment: production web_1 | WARNING: Do not use the development server in a production environment. web_1 | Use a production WSGI server instead. web_1 | * Debug mode: on web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) web_1 | * Restarting with stat web_1 | * Debugger is active! web_1 | * Debugger PIN: 151-215-059 redis_1 | 1:C 27 Jun 06:47:25.385 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 27 Jun 06:47:25.387 # Redis version=4.0.10, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 27 Jun 06:47:25.387 # 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 27 Jun 06:47:25.389 * Running mode=standalone, port=6379. redis_1 | 1:M 27 Jun 06:47:25.389 # 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 27 Jun 06:47:25.389 # Server initialized redis_1 | 1:M 27 Jun 06:47:25.389 # 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 27 Jun 06:47:25.389 * Ready to accept connections
pause:暫停一個服務容器,處於暫停狀態的容器,無法用start命令啓動
Usage: pause [SERVICE...]
# docker-compose pause Pausing composetest_redis_1 ... done Pausing composetest_web_1 ... done
docker-compose pause 暫停所有服務
port:顯示某個容器端口所映射的公共端口
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 web 5000 0.0.0.0:5000
ps:列出項目中所有容器
sage: ps [options] [SERVICE...] Options: -q Only display IDs
例如:
# docker-compose ps Name Command State Ports -------------------------------------------------------------------------------------- composetest_redis_1 docker-entrypoint.sh redis ... Paused 6379/tcp composetest_web_1 python app.py Paused 0.0.0.0:5000->5000/tcp
pull:拉取服務依賴的鏡像
Usage: pull [options] [SERVICE...] Options: --ignore-pull-failures Pull what it can and ignores images with pull failures. 忽略pull失敗的鏡像,繼續pull其他鏡像. --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
restart:重啓項目中的服務
Usage: restart [options] [SERVICE...] Options: -t, --timeout TIMEOUT Specify a shutdown timeout in seconds. (default: 10)
rm:刪除所有(停止狀態)的服務容器
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 刪除掛載的數據卷
run:在指定服務上指定一個命令
run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] SERVICE [COMMAND] [ARGS...] Options: -d, --detach 後臺運行容器 --name NAME 爲容器指定一個名字 --entrypoint CMD CMD 覆蓋默認的容器啓動指令 -e KEY=VAL 設置環境變量值,可以多次使用選項來設置多個環境變量 -l, --label KEY=VAL Add or override a label (can be used multiple times) -u, --user="" 執行容器運行的用戶名或UID --no-deps 不自動啓動關聯的服務容器 --rm 運行命令後自動刪除容器,d默認下將忽略 -p, --publish=[] 映射容器端口到本地主機 --service-ports 配置服務端口並映射到本地主機 --use-aliases Use the service's network aliases in the network(s) the container connects to. -v, --volume=[] Bind mount a volume (default []) -T 不分配僞TTY,意味着依賴tty的指令將無法運行 -w, --workdir="" Working directory inside the container
例如:
# docker-compose run web df -h Filesystem Size Used Available Use% Mounted on /dev/mapper/docker-253:1-33829585-e7823f93d92cd1917ac0d92d18af82bb437f68af6991a1f47d007a261cc0cd48 10.0G 133.8M 9.9G 1% / tmpfs 64.0M 0 64.0M 0% /dev tmpfs 1.8G 0 1.8G 0% /sys/fs/cgroup /dev/vda1 25.0G 15.3G 9.7G 61% /code /dev/vda1 25.0G 15.3G 9.7G 61% /etc/resolv.conf /dev/vda1 25.0G 15.3G 9.7G 61% /etc/hostname /dev/vda1 25.0G 15.3G 9.7G 61% /etc/hosts shm 64.0M 0 64.0M 0% /dev/shm tmpfs 64.0M 0 64.0M 0% /proc/kcore tmpfs 64.0M 0 64.0M 0% /proc/keys tmpfs 64.0M 0 64.0M 0% /proc/timer_list tmpfs 64.0M 0 64.0M 0% /proc/timer_stats tmpfs 64.0M 0 64.0M 0% /proc/sched_debug tmpfs 1.8G 0 1.8G 0% /proc/scsi tmpfs 1.8G 0 1.8G 0% /sys/firmware
scale:設置服務運行的容器個數,通過service=num來設置
Usage: scale [SERVICE=NUM...]
如:
docker-compose scale web=2 redis=2
start:啓動已經存在的服務容器
Usage: start [SERVICE...]
stop:停止處於運行狀態的容器服務,但不刪除,可以通過docker-compose start再次啓動
Usage: stop [options] [SERVICE...] Options: -t, --timeout TIMEOUT Specify a shutdown timeout in seconds (default: 10).
top:顯示正在運行的進程
Usage: top [SERVICE...]
例如:
[root@OPS01-LINTEST02 composetest]# docker-compose top composetest_redis_1 UID PID PPID C STIME TTY TIME CMD --------------------------------------------------------------- 100 18915 18888 0 15:39 ? 00:00:00 redis-server composetest_web_1 UID PID PPID C STIME TTY TIME CMD -------------------------------------------------------------------------------- root 18909 18880 0 15:39 ? 00:00:00 python app.py root 19015 18909 0 15:39 ? 00:00:03 /usr/local/bin/python app.py
unpause:恢復處於暫停狀態狀態中的服務
Usage: unpause [SERVICE...]
up:
Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...] Options: -d, --detach 後臺運行服務容器 --no-color 不使用顏色來區分不同的服務的控制檯輸出 --quiet-pull Pull without printing progress information --no-deps 不啓動服務所鏈接的容器 --force-recreate 強制重新創建容器,不能與--no-recreate同時使用 --always-recreate-deps Recreate dependent containers. Incompatible with --no-recreate. --no-recreate 如果容器已經存在,則不重新創建,不能與--force-recreate同時使用 them. Incompatible with --force-recreate and -V. --no-build 不自動構建缺失的服務鏡像 --no-start 創建容器後不啓動 --build Build images before starting containers. --abort-on-container-exit Stops all containers if any container was stopped. Incompatible with -d. -t, --timeout TIMEOUT 停止容器時候的超時時間,默認是10s -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選項,將後臺運行所有容器。如果容器已經存在,則docker-compose up將嘗試停止容器,然後重新創建(保持使用volumes-form掛載的卷),以保證新啓動的服務匹配最新的docker-compose.yml文件
如果不希望容器被停止並重新創建,使用--no-recreate,這樣只會啓動處於停止狀態的容器,而忽略已經運行的服務。如果用戶想要重新部署某個服務,可以使用--no-deps -d <SERVICE_NAME> 來重新
創建服務並後臺停止舊的服務,啓動新服務,並不會影響到其依賴的服務