# Dockerコマンド、Dockerfile・Compose file リファレンス

**URL:** https://forum.ficusonline.com/t/topic/128
**Category:** Server
**Created:** [2017 年 9 月 2 日午前 7:44 UTC](https://forum.ficusonline.com/t/topic/128 "2017-09-02T07:44:03Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2017 年 9 月 2 日午前 7:44 UTC](https://forum.ficusonline.com/t/topic/128/1 "2017-09-02T07:44:03Z")

</div>

### docker exec

コンテナ内でコマンド操作します。

例）container\_nameというコンテナに対し以下コマンドを実行します。（シェルの起動）

> $ docker exec -it container\_name /bin/bash

> **[docker container exec](https://docs.docker.com/reference/cli/docker/container/exec/)**

コンテナ内でrootユーザによる各種コマンド操作ができます。exitコマンドで終了します。

### docker-compose exec

docker-composeファイルにより各種コンテナを起動している場合には、サービス名を指定して以下コマンドでも同様の操作が可能です。

> $ docker-compose exec service\_name bash

> **[docker compose exec](https://docs.docker.com/reference/cli/docker/compose/exec/)**

### docker ps

格納コンテナは以下コマンドで確認できます。

> **[docker container ls](https://docs.docker.com/reference/cli/docker/container/ls/)**

> $sudo docker ps -a

以下lsコマンドによる出力結果と同じです。

> $ sudo docker container ls -a

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 6 月 13 日午前 8:57 UTC](https://forum.ficusonline.com/t/topic/128/2 "2019-06-13T08:57:56Z")

</div>

**使用頻度の高いdockerコマンドメモ**

- List images:  
**$ docker image ls**
- Pulling an **alpine** image:  
**$ docker image pull alpine**
- Run a container from a locally-available image:  
**$ docker container run -it alpine sh**
- Run a container in the background ( **-d** option) from an image:  
**$ docker container run -d nginx**
- List only running containers:  
**$ docker container ls**
- List all containers:  
**$ docker container ls -a**
- Inject a process inside a running container:  
**$ docker container exec -it \<container\_id/name\> bash**
- Stop a container:  
**$ docker container stop \<container id/name\>**
- Delete a container:  
**$ docker container rm \<container id/name\>**
- 不要なボリューム削除  
**$ docker volume prune --all**
- 不要なビルドキャッシュの削除  
**$ docker builder prune --all**
- キャッシュを無効にしてビルド  
**$ docker compose build --no-cache**
- Dockerfileからタグ付きでビルド  
**docker build -t vieux/apache:2.0 .**

[https://matsuand.github.io/docs.docker.jp.onthefly/engine/reference/commandline/build/](https://matsuand.github.io/docs.docker.jp.onthefly/engine/reference/commandline/build/)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 6 月 20 日午前 7:28 UTC](https://forum.ficusonline.com/t/topic/128/3 "2019-06-20T07:28:23Z")

</div>

### 不要なdocker imageの削除

> **[How To Remove Docker Images, Containers, and Volumes | DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-remove-docker-images-containers-and-volumes)**
>
> Learn how to remove Docker images, containers, and volumes. This guide covers Docker cleanup commands and manage containerized applications.

リストアップ（タグの無い`<none>`イメージファイルのリストアップ  
イメージ作成時にタグ付しないと不要なイメージとしてリストアップされるので注意）

```auto
$ docker images -f dangling=true -q

```

上記`<none>`タグのイメージ削除

```auto
$ docker rmi $(sudo docker images -f dangling=true -q)

```

または

```auto
$ docker image prune

```

注）docker rmi を実行してもディスクスペースが増えないのは、Docker が使用している仮想ディスクが拡張は自動的に行うが縮小は行われないためです。Docker イメージやコンテナのデータを削除しても、使われていたディスクスペースは空の状態で確保されたままとなっています。

ディスクスペースを開放するために、追加で下記コマンドを実行します。

> **[docker system prune](https://docs.docker.com/reference/cli/docker/system/prune/)**

全イメージが削除されます。

```auto
$ docker system prune -a

```

* * *

### 全コンテナの停止・削除

### コンテナリスト

```auto
$ docker ps -a

```

### 全コンテナ停止・削除

```auto
$ docker stop $(docker ps -a -q)
$ docker rm $(docker ps -a -q)

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 6 月 22 日午前 2:46 UTC](https://forum.ficusonline.com/t/topic/128/4 "2019-06-22T02:46:40Z")

</div>

**停止中のコンテナ一覧**

> <https://stackoverflow.com/questions/30231187/list-only-stopped-docker-containers>

> $ docker ps -f “status=exited”

イメージを削除する場合、事前にコンテナを削除する必要が有ります。

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 6 月 22 日午前 3:09 UTC](https://forum.ficusonline.com/t/topic/128/5 "2019-06-22T03:09:56Z")

</div>

**Docker pullコマンド：イメージのダウンロード・アップデート**

tagを指定しないとタグlatestがダウンロードされます。  
（latestでタグ付けされていないイメージの場合エラーとなります）

**ex)**

> $ docker pull divante/pimcore5-php:php-7.3-base

### イメージのアップデート

既存イメージのアップデートもpullコマンドで行います。  
（既存コンテナを削除、アップデート後コンテナを再構築）

**最新バージョン(tag:latest)へのアップデート・変更**

> $ docker pull divante/pimcore5-php

**Tag指定バージョンのアップデート**

> $ docker pull divante/pimcore5-php:php-7.3-base

> **[docker image pull](https://docs.docker.com/reference/cli/docker/image/pull/)**

**docker pull** コマンドによりアップデートされた旧イメージは、 **tag** が`<none>`表記になり、イメージIDを指定しても削除できない場合があります。

> **[Docker duplicate image with same image id with tag](https://forums.docker.com/t/docker-duplicate-image-with-same-image-id-with-tag-none/25241)**
>
> Hi there i am running docker on windows with quick start terminal and tried to pull the image ubuntu $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest ...

この場合、イメージダイジェストを下記コマンドで確認後、このダイジェストを指定して削除します。

```auto
$ docker images --digests
REPOSITORY TAG DIGEST IMAGE ID CREATED SIZE
nginx <none> sha256:763e7f0188e378fef0c761854552c70bbd817555dc4de029681a2e972e25e30e 89ec9da68213 8 months ago 19.9MB

```

`<none>`タグイメージの削除

```auto
$ docker rmi nginx@sha256:763e7f0188e378fef0c761854552c70bbd817555dc4de029681a2e972e25e30e 89ec9da68213  
Untagged: nginx@sha256:763e7f0188e378fef0c761854552c70bbd817555dc4de029681a2e972e25e30e

```

**Docker runコマンド**

オプションとしてコンテナ名、ポートなどを指定します。

> **[docker container run](https://docs.docker.com/reference/cli/docker/container/run/)**

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 6 月 26 日午前 3:17 UTC](https://forum.ficusonline.com/t/topic/128/6 "2019-06-26T03:17:06Z")

</div>

**Dockerコンテナへのファイルコピー**

ローカル端末から稼働コンテナへのウェブコンテンツコピーやコンテナ内ファイルのコピーなどに使用。

> **[docker container cp](https://docs.docker.com/reference/cli/docker/container/cp/)**

> <https://stackoverflow.com/questions/22907231/how-to-copy-files-from-host-to-docker-container>

ファイルコピー（ローカルファイル\<—\>コンテナ）

```auto
$ docker cp foo.txt mycontainer:/foo.txt
$ docker cp mycontainer:/foo.txt foo.txt

```

マルチファイルコピー（ローカルファイル\<—\>コンテナ）

```auto
$ docker cp src/. mycontainer:/target
$ docker cp mycontainer:/src/. target

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 6 月 27 日午前 1:59 UTC](https://forum.ficusonline.com/t/topic/128/7 "2019-06-27T01:59:01Z")

</div>

**Docker Compose**

複数コンテナ同時起動

> **[Quickstart](https://docs.docker.com/compose/gettingstarted/)**
>
> Follow this hands-on tutorial to learn how to use Docker Compose from defining application dependencies to experimenting with commands.

ex) **docker-compose.yml** ファイルを作成し、以下コマンドでコンテナ起動

```auto
version: '3.3'
services:
  freepbx:
    image: flaviostutz/freepbx:14.0
    network_mode: host
    restart: always
    volumes:
      - freepbx-backup:/backup
      - freepbx-recordings:/var/spool/asterisk/monitor

volumes:
  freepbx-backup:
  freepbx-recordings:

```

上記ファイルで定義したコンテナを同時起動（バックグラウンド）

> $ docker-compose up -d

稼働コンテナの確認

> $ docker-compose ps

停止コマンド

> $ docker-compose stop

### Docker-Composeファイルの内容を変更した場合

> **[docker compose up](https://docs.docker.com/reference/cli/docker/compose/up/)**

再度以下コマンドを実行して変更内容を反映させます。（各コンテナは稼働したままでOKです）

```auto
$ docker-compose up -d

```

この場合、変更箇所のサービスコンテナのみが初期化されます。  
このため上記サービスコンテナにおいて変更前に追加・修正した設定・ファイルは全て初期化・削除されます。

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 8 月 8 日午前 1:05 UTC](https://forum.ficusonline.com/t/topic/128/8 "2019-08-08T01:05:21Z")

</div>

**Docker Commit**

コンテナ内でアップデート、ファイルの追加・変更などをした内容を引継ぎ新たなイメージファイルを作成。

> **[docker container commit](https://docs.docker.com/reference/cli/docker/container/commit/)**

```auto
$ docker commit -m "What you did to the image" -a "Author Name" container_id repository/new_image_name

```

-m:メッセージオプション、-a:作成者

```auto
$ docker commit -m "apt updated" -a "Takanobu Fuse" fdg768888 takanobu/ubuntu:updated

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 8 月 24 日午前 5:55 UTC](https://forum.ficusonline.com/t/topic/128/9 "2019-08-24T05:55:31Z")

</div>

**コンテナログ確認**

> **[docker container logs](https://docs.docker.com/reference/cli/docker/container/logs/)**

```auto
$ docker logs [OPTIONS] CONTAINER

```

> **[docker compose logs](https://docs.docker.com/reference/cli/docker/compose/logs/)**

```auto
$ docker compose logs [OPTIONS] [SERVICE...]

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 8 月 25 日午後 11:56 UTC](https://forum.ficusonline.com/t/topic/128/10 "2019-08-25T23:56:12Z")

</div>

## Dockerコンテナ設定変更（アップデート）

> **[docker container update](https://docs.docker.com/reference/cli/docker/container/update/)**

## Dockerコンテナの自動起動変更

> **[Start containers automatically](https://docs.docker.com/engine/containers/start-containers-automatically/)**
>
> How to start containers automatically

| Flag | Description |
| --- | --- |
| `no` | Do not automatically restart the container. (the default) |
| `on-failure[:max-retries]` | Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the `:max-retries` option. |
| `always` | Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in [restart policy details](https://docs.docker.com/config/containers/start-containers-automatically/#restart-policy-details)) |
| `unless-stopped` | Similar to `always`, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. |

**ホストマシン再起動後起動しない場合**

```auto
$ docker update --restart no CONTAINER_NAME(or ID)

```

**ホストマシン再起動後も起動する場合**

```auto
$ docker run -d --restart unless-stopped redis

```

既に起動しているコンテナの設定を **”ホストマシン再起動後も起動する”に変更** する場合

```auto
$ docker update --restart unless-stopped redis

```

**全てのコンテナに上記変更内容を適用する場合**

```auto
$ docker update --restart unless-stopped $(docker ps -q)

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 10 月 30 日午前 2:54 UTC](https://forum.ficusonline.com/t/topic/128/11 "2019-10-30T02:54:53Z")

</div>

**Docker Volume**

ホストとコンテナ間でファイルを共有する際に設定します。ホスト側でボリューム名のみ指定した場合は、 **/var/lib/docker/volumes** に指定したボリューム名のフォルダが作成されます。

### ex1) ホスト側shared, vhost, htmlフォルダは/var/lib/docker/volumesに作成されます。

**注）** _コンテナ側のディレクトリの内容がホスト側に反映されます。コンテナ内のディレクトリをホスト側で参照したい場合には、こちらを利用します。_

```auto
    volumes:
      - shared:/etc/nginx/certs
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html

```

> <https://stackoverflow.com/questions/59159241/how-to-map-a-docker-containers-directory-to-the-host-with-docker-compose>

### ex2) ホスト側shared, vhost, htmlフォルダは指定ディレクトリに作成されます。

**注）** _ホスト側に指定デイレクトリが存在しない場合、ホスト側に新たに新規ディレクトリが作成され、コンテナ内の指定ディレクトリにマウントされます。このためコンテナ側のディレクトリの中身が空になります。_

```auto
    volumes:
      - ./shared:/etc/nginx/certs
      - ./vhost:/etc/nginx/vhost.d
      - ~/html:/usr/share/nginx/html

```

> **[Volumes](https://docs.docker.com/engine/storage/volumes/)**
>
> Learn how to create, manage, and use volumes instead of bind mounts for persisting data generated and used by Docker.

```auto
$ docker volume help

Usage:	docker volume COMMAND

Manage volumes

Commands:
  create Create a volume
  inspect Display detailed information on one or more volumes
  ls List volumes
  prune Remove all unused local volumes
  rm Remove one or more volumes

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

```

不要なVolumeの削除

```auto
$ docker volume prune --all

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 11 月 10 日午前 4:52 UTC](https://forum.ficusonline.com/t/topic/128/12 "2019-11-10T04:52:42Z")

</div>

### Docker-Compose 外部ボリューム

> **[Compose file reference](https://docs.docker.com/reference/compose-file/)**
>
> Find the latest recommended version of the Docker Compose file format for defining multi-container applications.

composeによるコンテナ外のVolumeを参照する場合、予めdockerコマンドによりボリュームを作成。

```auto
$ docker volume create data

```

### docker-composeファイルで外部ボリューム “data” を指定(external)

```auto
version: "3.7"

services:
  db:
    image: postgres
    volumes:
      - data:/var/lib/postgresql/data

volumes:
  data:
    external: true

```

**ボリューム名による指定(external)**

```auto
volumes:
  data:
    external:
      name: actual-name-of-volume

```

**ホストーコンテナ間のボリューム相関関係**

単一ディレクトリを指定した場合、コンテナが指定ディレクトリを作成。  
その他、ホスト側の絶対パス、相対パス、外部ボリューム名などを表します。

> **[Legacy versions](https://docs.docker.com/reference/compose-file/legacy-versions/)**

```auto
volumes:
  # Just specify a path and let the Engine create a volume
  - /var/lib/mysql

  # Specify an absolute path mapping
  - /opt/data:/var/lib/mysql

  # Path on the host, relative to the Compose file
  - ./cache:/tmp/cache

  # User-relative path
  - ~/configs:/etc/configs/:ro

  # Named volume
  - datavolume:/var/lib/mysql

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 11 月 12 日午前 3:01 UTC](https://forum.ficusonline.com/t/topic/128/13 "2019-11-12T03:01:24Z")

</div>

## Dockerfile portオプション：-p(publish)とexposeの違い

### -p(publish):

ホストとコンテナ間のポートを定義。 ex) ホストポート：コンテナポート —\> 80:8080  
dockerネットワーク外部からホストのポートを経由してコンテナにアクセス可。  
このオプションは以下のexposeオプションを包括。

### expose:

コンテナのポートを定義。dockerネットワーク内でのみポートを指定してアクセス可。

> **[Dockerfile reference](https://docs.docker.com/reference/dockerfile)**
>
> Find all the available commands you can use in a Dockerfile and learn how to use them, including COPY, ARG, ENTRYPOINT, and more.

> <https://stackoverflow.com/questions/22111060/what-is-the-difference-between-expose-and-publish-in-docker>

## Docker-Compose file “expose”, “ports”

**expose**

> **[Legacy versions](https://docs.docker.com/reference/compose-file/legacy-versions/)**

**ports**

> **[Legacy versions](https://docs.docker.com/reference/compose-file/legacy-versions/)**

**稼働コンテナのネットワークの確認**

```auto
$ docker inspect CONTAINER_NAME

```

**ports:** ホストマシンとコンテナのポートがマッピングされている場合

```auto
"Ports": {
                "443/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "443"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "443"
                    }
                ],
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "80"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "80"
                    }
                ]
            },

```

**expose:** Dockerネットワーク内のみでポート開放している場合

```auto
"Ports": {
                "6379/tcp": null
            },

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 11 月 13 日午後 3:19 UTC](https://forum.ficusonline.com/t/topic/128/14 "2019-11-13T15:19:05Z")

</div>

### Docker Networks: DockerコンテナへのIPアドレスのアサイン

**subnetを指定してdockerネットワークを作成後、IPアドレスをアサインしてコンテナを起動**

> <https://stackoverflow.com/questions/27937185/assign-static-ip-to-docker-container>

```auto
docker network create --subnet=172.18.0.0/16 mynet123

```

`--ip` オプションでIPアドレスを指定してコンテナを起動

```auto
docker run --net mynet123 --ip 172.18.0.22 -it ubuntu bash

```

**Docker-Composeファイルで指定する場合**

> **[Legacy versions](https://docs.docker.com/reference/compose-file/legacy-versions/)**

```auto
version: "3.7"

services:
  app:
    image: nginx:alpine
    networks:
      app_net:
        ipv4_address: 172.16.238.10
        ipv6_address: 2001:3984:3989::10

networks:
  app_net:
    ipam:
      driver: default
      config:
        - subnet: "172.16.238.0/24"
        - subnet: "2001:3984:3989::/64"

```

**ipam** (IP Address Manager)により、ネットワークモード、サブネットマスク等を指定

**ネットワーク設定リファレンス**

その他の設定オプションについては、上記同ページの以下参照のこと。

> **[Legacy versions](https://docs.docker.com/reference/compose-file/legacy-versions/)**

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2019 年 11 月 14 日午後 3:09 UTC](https://forum.ficusonline.com/t/topic/128/15 "2019-11-14T15:09:32Z")

</div>

### Compose file: depends\_on

> **[Compose file reference](https://docs.docker.com/reference/compose-file/)**
>
> Find the latest recommended version of the Docker Compose file format for defining multi-container applications.

ex) `depend_on`で指定したサービス **db** , **redis** を起動後、 **web** サービスを開始。

```auto
version: "3.7"
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 3 月 4 日午前 3:05 UTC](https://forum.ficusonline.com/t/topic/128/16 "2020-03-04T03:05:37Z")

</div>

### Docker-Compose Build

DockerfileによりDocker Hub: [https://hub.docker.com/](https://hub.docker.com/) 等から提供されているイメージを元にカスタムイメージを作成できますが、Docker-Composeファイル内でもこの作業が行えます。

> **[Compose file reference](https://docs.docker.com/reference/compose-file/)**
>
> Find the latest recommended version of the Docker Compose file format for defining multi-container applications.

```auto
version: "3.7"
services:
  webapp:
    build:
      context: ./dir
      dockerfile: Dockerfile-alternate
      args:
        buildno: 1
    image: webapp:tag

```

webapp —\> イメージ名  
context —\> Dockerfileディレクトリ：./dir  
dockerfile —\> Dockerfile-alternate  
args —\> ビルド時のみ使用される環境変数  
image —\> イメージ名：タグ

* * *

Docker Composeファイルでビルドしたイメージを再ビルドする場合、イメージ作成過程の各プロセスでキャッシュされたボリュームが再利用されます。このキャッシュボリュームを利用したくない場合は **`--no-cache`** オプションを付与して再ビルドします。

```auto
$ docker compose --no-cache build SERVICE

```

> <https://stackoverflow.com/questions/36884991/how-to-rebuild-docker-container-in-docker-compose-yml>

ビルドキャッシュの削除

```auto
$ docker builder prune --all

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 3 月 4 日午前 8:58 UTC](https://forum.ficusonline.com/t/topic/128/17 "2020-03-04T08:58:42Z")

</div>

### Dockerfile RUN CMD ENTRYPOINT

### RUN

以下shellとexecの2種類のフォームで記述します。イメージに新たなパッケージを追加する際等に使用します。

- `RUN <command>` ( _shell_ form, the command is run in a shell, which by default is `/bin/sh -c` on Linux or `cmd /S /C` on Windows)  
/bin/shシェルにより各コマンドが実行される。一連のコマンドを実行した場合、次のコマンドに変数などが引き継がれる。

- `RUN ["executable", "param1", "param2"]` ( _exec_ form)  
シェル無しでコマンドを直接実行。/bin/bashを使用する場合もこのフォームを使用する。

> **[Dockerfile reference](https://docs.docker.com/reference/dockerfile)**
>
> Find all the available commands you can use in a Dockerfile and learn how to use them, including COPY, ARG, ENTRYPOINT, and more.

**RUNインストラクション**

> **[Best practices](https://docs.docker.com/build/building/best-practices/)**
>
> Hints, tips and guidelines for writing clean, reliable Dockerfiles

以下apt-get update と apt-get install はセットで記述すること。別々に記述するとupdateのキャッシュされた古いデータからパッケージがアップデートされるため。

```auto
RUN apt-get update && apt-get install -y \
    package-bar \
    package-baz \
    package-foo

```

### CMD

以下RUNと同様なexecとshellフォームに加え、ENTRYPOINTのパラメータとしてのフォームがあります。Dockerコンテナ内で実行されるデフォルトのコマンドを指定。複数のCMDを指定した場合、最後のCMDのみ有効。

- `CMD ["executable","param1","param2"]` ( _exec_ form, this is the preferred form)
- `CMD ["param1","param2"]` (as _default parameters to ENTRYPOINT_ )
- `CMD command param1 param2` ( _shell_ form)

> **[Dockerfile reference](https://docs.docker.com/reference/dockerfile)**
>
> Find all the available commands you can use in a Dockerfile and learn how to use them, including COPY, ARG, ENTRYPOINT, and more.

### ENTRYPOINT

RUNと同様、以下のexecまたはshellフォームで記述します。コンテナ起動時に必ず実行されるコマンドで、ENTRYPOINTに続けてCMDを指定すると、CMDがENTRYPOINTの引数になります。

- `ENTRYPOINT ["executable", "param1", "param2"]` ( _exec_ form, preferred)
- `ENTRYPOINT command param1 param2` ( _shell_ form)

> **[Dockerfile reference](https://docs.docker.com/reference/dockerfile)**
>
> Find all the available commands you can use in a Dockerfile and learn how to use them, including COPY, ARG, ENTRYPOINT, and more.

### Understand how CMD and ENTRYPOINT interact

Both `CMD` and `ENTRYPOINT` instructions define what command gets executed when running a container. There are few rules that describe their co-operation.

1. Dockerfile should specify at least one of `CMD` or `ENTRYPOINT` commands.
2. `ENTRYPOINT` should be defined when using the container as an executable.
3. `CMD` should be used as a way of defining default arguments for an `ENTRYPOINT` command or for executing an ad-hoc command in a container.
4. `CMD` will be overridden when running the container with alternative arguments.

The table below shows what command is executed for different `ENTRYPOINT` / `CMD` combinations:

| | No ENTRYPOINT | ENTRYPOINT exec\_entry p1\_entry | ENTRYPOINT [“exec\_entry”, “p1\_entry”] |
| --- | --- | --- | --- |
| **No CMD** | _error, not allowed_ | /bin/sh -c exec\_entry p1\_entry | exec\_entry p1\_entry |
| **CMD [“exec\_cmd”, “p1\_cmd”]** | exec\_cmd p1\_cmd | /bin/sh -c exec\_entry p1\_entry | exec\_entry p1\_entry exec\_cmd p1\_cmd |
| **CMD [“p1\_cmd”, “p2\_cmd”]** | p1\_cmd p2\_cmd | /bin/sh -c exec\_entry p1\_entry | exec\_entry p1\_entry p1\_cmd p2\_cmd |
| **CMD exec\_cmd p1\_cmd** | /bin/sh -c exec\_cmd p1\_cmd | /bin/sh -c exec\_entry p1\_entry | exec\_entry p1\_entry /bin/sh -c exec\_cmd p1\_cmd |

### CMDとENTRYPOINTの違い

> <https://stackoverflow.com/questions/21553353/what-is-the-difference-between-cmd-and-entrypoint-in-a-dockerfile>

### 一つのコンテナ内でマルチサービスを実行

> **[Run multiple processes in a container](https://docs.docker.com/engine/containers/multi-service_container/)**
>
> Learn how to run more than one process in a single container

If you have one main process that needs to start first and stay running but you temporarily need to run some other processes (perhaps to interact with the main process) then you can use bash’s job control to facilitate that. First, the wrapper script:

```auto
#!/bin/bash
  
# turn on bash's job control
set -m
  
# Start the primary process and put it in the background
./my_main_process &
  
# Start the helper process
./my_helper_process
  
# the my_helper_process might need to know how to wait on the
# primary process to start before it does its work and returns
  
  
# now we bring the primary process back into the foreground
# and leave it there
fg %1

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 3 月 14 日午後 2:11 UTC](https://forum.ficusonline.com/t/topic/128/18 "2020-03-14T14:11:52Z")

</div>

### Dockerfile COPY

> **[Dockerfile reference](https://docs.docker.com/reference/dockerfile)**
>
> Find all the available commands you can use in a Dockerfile and learn how to use them, including COPY, ARG, ENTRYPOINT, and more.

> <https://stackoverflow.com/questions/30215830/dockerfile-copy-keep-subdirectory-structure>

**host\_folder** の中身を全て **docker\_folder/sub\_folder** にコピーする場合（host\_folder/\*としない）

```auto
COPY host_folder/ /docker_folder/sub_folder/

```

### Dockerfile ADD or COPY

> **[Best practices](https://docs.docker.com/build/building/best-practices/)**
>
> Hints, tips and guidelines for writing clean, reliable Dockerfiles

> <https://stackoverflow.com/questions/24958140/what-is-the-difference-between-the-copy-and-add-commands-in-a-dockerfile>

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 3 月 14 日午後 2:20 UTC](https://forum.ficusonline.com/t/topic/128/19 "2020-03-14T14:20:30Z")

</div>

### Compose file: command

> **[Compose file reference](https://docs.docker.com/reference/compose-file/)**
>
> Find the latest recommended version of the Docker Compose file format for defining multi-container applications.

> <https://stackoverflow.com/questions/30063907/docker-compose-how-to-execute-multiple-commands>

**bash -c によるマルチコマンド実行例**

```auto
command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"

```

### 適用例）

**DockerHub Mariadbの文字コードをcommandで指定**

> **[mariadb - Official Image | Docker Hub](https://hub.docker.com/_/mariadb?tab=description)**
>
> MariaDB Server is a high performing open source relational database, forked from MySQL.

デフォルトでは **latin1** に設定されるため、事前に **utf8mb4** を指定。

> <https://stackoverflow.com/questions/45729326/how-to-change-the-default-character-set-of-mysql-using-docker-compose>

```auto
command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci']

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 3 月 15 日午前 9:53 UTC](https://forum.ficusonline.com/t/topic/128/20 "2020-03-15T09:53:14Z")

</div>

### Docker CLI: docker image inspect/docker inspect

Dockerイメージの詳細表示

> **[docker image inspect](https://docs.docker.com/reference/cli/docker/image/inspect/)**

Dockerコンテナの詳細表示

> **[docker inspect](https://docs.docker.com/reference/cli/docker/inspect/)**

[次のページ](https://forum.ficusonline.com/t/topic/128.md?page=2)
