LoginSignup
211
214

More than 5 years have passed since last update.

docker-composeでよく使うコマンド

Last updated at Posted at 2019-02-11

1_QVFjsW8gyIXeCUJucmK4XA.png

背景

docker-composeを雰囲気で使っているのでコマンドの意味を再確認する意味もかねて記事を作成

docker-composeとは

yaml形式の設定ファイルで複数コンテナを実行を一括で管理できるツール
インストールなどは別記事をご参照ください。
Docker Compose のインストール

環境

$ docker --version
Docker version 18.09.1, build 4c52b90

$ docker-compose --version
docker-compose version 1.22.0, build f46880f

とりあえずhelp

buildやup,down等の基本コマンド以外を打つときはまずhelp見ます。
これでもわからなければネットなどで調べてます。

$ sudo docker-compose help
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 deploy
                              keys in v3 files to their non-Swarm equivalent

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

ビルド

サービスをビルドします。
サービス名を指定してビルドすることもできます。
「--no-cache」等も指定できます。

$ sudo docker-compose build

## サービスを指定してビルド
$ sudo docker-compose build nginx

## Usage
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.

起動/停止/再起動

up,downでサービスの起動停止を行います。

downとstopの違いは公式より下記のように記載されています。
downは「コンテナ・ネットワーク・イメージ・ボリュームの停止と削除」
stopは「サービスの停止」

# 起動
$ sudo docker-compose up
## バックグラウンド実行なら「-d」を付けてup
$ sudo docker-compose up -d
## サービスを指定して起動するなら
$ sudo docker-compose up nginx

# 停止
$ sudo docker-compose stop
## 停止かつコンテナを削除
$ sudo docker-compose down
## イメージも合わせて削除
$ sudo docker-compose down --rmi all

# 再起動
$ sudo docker-compose restart

yamlの確認

docker-compose.ymlで書かれてる内容が表示されます。
どのようなサービスで構成されているか確認するオプション「--service」もあります。
書き方に誤りがあるときはエラーを出力してくれます。
up前に確認したりするのに使ってます。

$ sudo docker-compose config
services:
  db:
    image: postgres
  web:
    build:
      context: /root/work/docker-compose
    command: python manage.py runserver 0.0.0.0:8000
    depends_on:
    - db
    ports:
    - 8000:8000/tcp
    volumes:
    - /root/work/docker-compose:/code:rw
version: '2.0'

## サービス名だけ取得
$ docker-compose config --service
db
web

## エラーがあるとき
$ sudo docker-compose config
ERROR: yaml.scanner.ScannerError: while scanning a simple key
  in "./docker-compose.yml", line 14, column 3
could not find expected ':'
  in "./docker-compose.yml", line 15, column 1

create

構築されたサービスを参考にそのコンテナを作ります。
ここで作られたコンテナは起動している状態ではありません。
これもまた引数にサービス名を指定して、特定のサービスだけのコンテナを作ることも可能です。

$ docker-compose create
Creating db_1
Creating web_1

## サービス名を指定
$ sudo docker-compose create db

events

コンテナからのイベントを受信します。

$ docker-compose events

## Usage
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.

exec

docker execコマンドと同等のことができます。
引数にサービス名と実行するコマンドを指定して実行します。

$ docker-compose exec web /bin/bash

images

対象のイメージの情報を表示します。

$ sudo docker-compose images
     Container             Repository        Tag       Image Id      Size
--------------------------------------------------------------------------
docker-compose_db_1    postgres             latest   5a02f920193b   298 MB
docker-compose_web_1   docker-compose_web   latest   1b7d48087d77   870 MB

kill

コンテナを強制停止します。
シグナルを指定して送ることも可能です。

## usage
Force stop service containers.
Usage: kill [options] [SERVICE...]
Options:
    -s SIGNAL         SIGNAL to send to the container.
                      Default signal is SIGKILL.

$ sudo docker-compose kill
Killing rails5product_web_1 ... done
Killing rails5product_db_1 ... done

logs

サービスのログを出力します。
また引数でサービス名を指定できるので、そうするとサービスごとにログを出力してくれます。

$ docker-compose logs

## ログをリアルタイム追跡(tailfのように出力「-t」で時間も)
$ sudo docker-compose logs -ft
db_1   | 2019-02-11T02:21:46.417460752Z The database cluster will be initialized with locale "en_US.utf8".
db_1   | 2019-02-11T02:21:46.417466610Z The default database encoding has accordingly been set to "UTF8".
db_1   | 2019-02-11T02:21:46.417487267Z The default text search configuration will be set to "english".

pause

サービスを一旦停止します。
勿論サービスごとに一時停止も可能です。

$ docker-compose pause
Pausing db_1 ... done
Pausing web_1 ... done

port

割り当てているポートを表示します。引数でサービス名とポート番号が必要になります。
tcp,udpでプロトコルの指定も可能です。

## usage
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]

$ sudo docker-compose port web 3000
0.0.0.0:3000

ps

コンテナの一覧を表示します。

$ sudo docker-compose ps
        Name                      Command               State     Ports
-------------------------------------------------------------------------
docker-compose_db_1    docker-entrypoint.sh postgres    Up       5432/tcp
docker-compose_db_2    docker-entrypoint.sh postgres    Up       5432/tcp
docker-compose_web_1   python manage.py runserver ...   Exit 2

## サービス名でも確認できます
$ sudo docker-compose ps web
        Name                      Command               State    Ports
----------------------------------------------------------------------
docker-compose_web_1   python manage.py runserver ...   Exit 2

pull

サービスのイメージをプルしてきます。

$ sudo docker-compose pull

## Usage
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

rm

停止中のコンテナを削除します。
起動中のコンテナも削除するならば「-f」を指定してください

$ sudo docker-compose rm 

## 強制削除
$ sudo docker-compose rm -f

scale

サービスを実行するコンテナ数を指定します

$ sudo docker-compose scale db=2
WARNING: The scale command is deprecated. Use the up command with the --scale flag instead.
Starting docker-compose_db_1 ... done
Creating docker-compose_db_2 ... done

こちらは現在は非推奨とのこと。コメントありがとうございます。
Docker Compose 1.13.0から「scale」が非推奨になり、「up --scale」に

top

各コンテナのプロセス情報を表示します。

$ sudo docker-compose top
docker-compose_db_1
  UID       PID    PPID    C   STIME   TTY     TIME                      CMD
----------------------------------------------------------------------------------------------
logstash   15251   14858   0   11:21   ?     00:00:00   postgres: stats collector
logstash   15252   14858   0   11:21   ?     00:00:00   postgres: logical replication launcher

docker-compose_db_2
  UID       PID    PPID    C   STIME   TTY     TIME                      CMD
----------------------------------------------------------------------------------------------
logstash   28206   28009   0   11:46   ?     00:00:00   postgres: stats collector
logstash   28207   28009   0   11:46   ?     00:00:00   postgres: logical replication launcher

まとめ

とりあえずこれ使えれば問題あっても調査の足掛かりにはなると思う。

参考リンク

公式リファレンス
docker-composeを使うと複数コンテナの管理が便利に
docker-compose コマンドまとめ

211
214
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
211
214