Use bind mountsバインドマウントの使用

In part 4, you used a volume mount to persist the data in your database. A volume mount is a great choice when you need somewhere persistent to store your application data.前のパート 4では、データベース内のデータを永続化するためにボリュームマウントを使用しました。ボリュームマウントは、アプリケーションデータを保存するための永続的な場所が必要な場合に最適な選択です。

A bind mount is another type of mount, which lets you share a directory from the host's filesystem into the container. When working on an application, you can use a bind mount to mount source code into the container. The container sees the changes you make to the code immediately, as soon as you save a file. This means that you can run processes in the container that watch for filesystem changes and respond to them.バインドマウントは別のタイプのマウントで、ホストのファイルシステムからコンテナにディレクトリを共有することができます。アプリケーションの作業を行う際に、ソースコードをコンテナにマウントするためにバインドマウントを使用できます。コンテナは、ファイルを保存するとすぐにコードに加えた変更を即座に認識します。これにより、ファイルシステムの変更を監視し、それに応じて反応するプロセスをコンテナ内で実行できます。

In this chapter, you'll see how you can use bind mounts and a tool called nodemon to watch for file changes, and then restart the application automatically. There are equivalent tools in most other languages and frameworks.この章では、バインドマウントと、ファイルの変更を監視し、アプリケーションを自動的に再起動するためのツールであるnodemonの使用方法を説明します。他の多くの言語やフレームワークにも同様のツールがあります。

Quick volume type comparisonsボリュームタイプの簡易比較

The following are examples of a named volume and a bind mount using --mount:以下は、--mountを使用した名前付きボリュームとバインドマウントの例です:

  • Named volume: type=volume,src=my-volume,target=/usr/local/data名前付きボリューム:type=volume,src=my-volume,target=/usr/local/data
  • Bind mount: type=bind,src=/path/to/data,target=/usr/local/dataバインドマウント:type=bind,src=/path/to/data,target=/usr/local/data

The following table outlines the main differences between volume mounts and bind mounts.以下の表は、ボリュームマウントとバインドマウントの主な違いを示しています。

Named volumes名前付きボリュームBind mountsバインドマウント
Host locationホストの場所Docker choosesDockerが選択しますYou decideあなたが決定します
Populates new volume with container contents新しいボリュームにコンテナの内容を格納しますYesはいNo
Supports Volume DriversボリュームドライバーをサポートしますYesはいNo

Trying out bind mountsバインドマウントの試用

Before looking at how you can use bind mounts for developing your application, you can run a quick experiment to get a practical understanding of how bind mounts work.アプリケーションの開発にバインドマウントをどのように使用できるかを見る前に、 bind mountsがどのように機能するかを実際に理解するための簡単な実験を行うことができます。

  1. Verify that your getting-started-app directory is in a directory defined in Docker Desktop's file sharing setting. This setting defines which parts of your filesystem you can share with containers. For details about accessing the setting, see File sharing.あなたの getting-started-app ディレクトリが、Docker Desktopのファイル共有設定で定義されたディレクトリにあることを確認してください。この設定は、コンテナと共有できるファイルシステムの部分を定義します。設定へのアクセスの詳細については、ファイル共有を参照してください。

    Note

    The File sharing tab is only available in Hyper-V mode, because the files are automatically shared in WSL 2 mode and Windows container mode.ファイル共有 タブはHyper-Vモードでのみ利用可能です。なぜなら、WSL 2モードとWindowsコンテナモードではファイルが自動的に共有されるからです。

  2. Open a terminal and change directory to the getting-started-app directory.ターミナルを開き、getting-started-app ディレクトリに移動します。

  3. Run the following command to start bash in an ubuntu container with a bind mount.次のコマンドを実行して、ubuntu コンテナ内でバインドマウントを使用して bash を開始します。

    $ docker run -it --mount type=bind,src="$(pwd)",target=/src ubuntu bash
    

    The --mount type=bind option tells Docker to create a bind mount, where src is the current working directory on your host machine (getting-started-app), and target is where that directory should appear inside the container (/src).--mount type=bind オプションは、Dockerにバインドマウントを作成するよう指示します。ここで src はホストマシンの現在の作業ディレクトリ(getting-started-app)であり、target はそのディレクトリがコンテナ内で表示される場所(/src)です。

  4. After running the command, Docker starts an interactive bash session in the root directory of the container's filesystem.コマンドを実行すると、Dockerはコンテナのファイルシステムのルートディレクトリでインタラクティブな bash セッションを開始します。

    root@ac1237fad8db:/# pwd
    /
    root@ac1237fad8db:/# ls
    bin   dev  home  media  opt   root  sbin  srv  tmp  var
    boot  etc  lib   mnt    proc  run   src   sys  usr
    
  5. Change directory to the src directory.srcディレクトリに移動します。

    This is the directory that you mounted when starting the container. Listing the contents of this directory displays the same files as in the getting-started-app directory on your host machine.これは、コンテナを起動する際にマウントしたディレクトリです。このディレクトリの内容をリストすると、ホストマシンのgetting-started-appディレクトリと同じファイルが表示されます。

    root@ac1237fad8db:/# cd src
    root@ac1237fad8db:/src# ls
    Dockerfile  node_modules  package.json  spec  src  yarn.lock
    
  6. Create a new file named myfile.txt.myfile.txtという名前の新しいファイルを作成します。

    root@ac1237fad8db:/src# touch myfile.txt
    root@ac1237fad8db:/src# ls
    Dockerfile  myfile.txt  node_modules  package.json  spec  src  yarn.lock
    
  7. Open the getting-started-app directory on the host and observe that the myfile.txt file is in the directory.ホストのgetting-started-appディレクトリを開き、myfile.txtファイルがそのディレクトリにあることを確認します。

    ├── getting-started-app/
    │ ├── Dockerfile
    │ ├── myfile.txt
    │ ├── node_modules/
    │ ├── package.json
    │ ├── spec/
    │ ├── src/
    │ └── yarn.lock
  8. From the host, delete the myfile.txt file.ホストからmyfile.txtファイルを削除します。

  9. In the container, list the contents of the app directory once more. Observe that the file is now gone.コンテナ内で再度appディレクトリの内容をリストします。ファイルがなくなっていることを確認します。

    root@ac1237fad8db:/src# ls
    Dockerfile  node_modules  package.json  spec  src  yarn.lock
    
  10. Stop the interactive container session with Ctrl + D.Ctrl + Dでインタラクティブなコンテナセッションを停止します。

That's all for a brief introduction to bind mounts. This procedure demonstrated how files are shared between the host and the container, and how changes are immediately reflected on both sides. Now you can use bind mounts to develop software.これでバインドマウントの簡単な紹介は終了です。この手順では、ホストとコンテナ間でファイルがどのように共有され、変更が両方に即座に反映されるかを示しました。これで、バインドマウントを使用してソフトウェアを開発できます。

Development containers開発コンテナ

Using bind mounts is common for local development setups. The advantage is that the development machine doesn’t need to have all of the build tools and environments installed. With a single docker run command, Docker pulls dependencies and tools.バインドマウントを使用することは、ローカル開発環境で一般的です。利点は、開発マシンにすべてのビルドツールや環境をインストールする必要がないことです。単一のdocker runコマンドで、Dockerは依存関係とツールを取得します。

Run your app in a development containerアプリを開発コンテナで実行する

The following steps describe how to run a development container with a bind mount that does the following:以下の手順では、次のことを行うバインドマウントを使用して開発コンテナを実行する方法を説明します:

  • Mount your source code into the containerソースコードをコンテナにマウントする
  • Install all dependenciesすべての依存関係をインストールする
  • Start nodemon to watch for filesystem changesnodemonを起動してファイルシステムの変更を監視する

You can use the CLI or Docker Desktop to run your container with a bind mount.CLIまたはDocker Desktopを使用して、バインドマウントでコンテナを実行できます。

  1. Make sure you don't have any getting-started containers currently running.getting-startedコンテナが現在実行中でないことを確認してください。

  2. Run the following command from the getting-started-app directory.getting-started-appディレクトリから次のコマンドを実行します。

    $ docker run -dp 127.0.0.1:3000:3000 \
        -w /app --mount type=bind,src="$(pwd)",target=/app \
        node:lts-alpine \
        sh -c "yarn install && yarn run dev"
    

    The following is a breakdown of the command:以下はコマンドの内訳です:

    • -dp 127.0.0.1:3000:3000 - same as before. Run in detached (background) mode and create a port mapping-dp 127.0.0.1:3000:3000 - 前と同じです。デタッチ(バックグラウンド)モードで実行し、ポートマッピングを作成します
    • -w /app - sets the "working directory" or the current directory that the command will run from-w /app - "作業ディレクトリ"、つまりコマンドが実行される現在のディレクトリを設定します。
    • --mount type=bind,src="$(pwd)",target=/app - bind mount the current directory from the host into the /app directory in the container--mount type=bind,src="$(pwd)",target=/app - ホストの現在のディレクトリをコンテナ内の/appディレクトリにバインドマウントします。
    • node:lts-alpine - the image to use. Note that this is the base image for your app from the Dockerfilenode:lts-alpine - 使用するイメージです。これはDockerfileからのアプリのベースイメージであることに注意してください。
    • sh -c "yarn install && yarn run dev" - the command. You're starting a shell using sh (alpine doesn't have bash) and running yarn install to install packages and then running yarn run dev to start the development server. If you look in the package.json, you'll see that the dev script starts nodemon.sh -c "yarn install && yarn run dev" - コマンドです。shを使用してシェルを起動し(alpineにはbashがありません)、yarn installを実行してパッケージをインストールし、その後yarn run devを実行して開発サーバーを起動します。package.jsonを見ると、devスクリプトがnodemonを起動することがわかります。
  3. You can watch the logs using docker logs <container-id>. You'll know you're ready to go when you see this:ログを確認するには、docker logs <container-id>を使用します。これが表示されたら、準備が整ったことがわかります:

    $ docker logs -f <container-id>
    nodemon -L src/index.js
    [nodemon] 2.0.20
    [nodemon] to restart at any time, enter `rs`
    [nodemon] watching path(s): *.*
    [nodemon] watching extensions: js,mjs,json
    [nodemon] starting `node src/index.js`
    Using sqlite database at /etc/todos/todo.db
    Listening on port 3000
    

    When you're done watching the logs, exit out by hitting Ctrl+C.ログの確認が終わったら、Ctrl+Cを押して終了します。

Develop your app with the development container開発コンテナを使用してアプリを開発する

Update your app on your host machine and see the changes reflected in the container.ホストマシン上でアプリを更新し、コンテナに変更が反映されるのを確認してください。

  1. In the src/static/js/app.js file, on line 109, change the "Add Item" button to simply say "Add":src/static/js/app.jsファイルの109行目で、「Add Item」ボタンを単に「Add」と言うように変更します:

    - {submitting ? 'Adding...' : 'Add Item'}
    + {submitting ? 'Adding...' : 'Add'}
    

    Save the file.ファイルを保存します。

  2. Refresh the page in your web browser, and you should see the change reflected almost immediately because of the bind mount. Nodemon detects the change and restarts the server. It might take a few seconds for the Node server to restart. If you get an error, try refreshing after a few seconds.ウェブブラウザでページをリフレッシュすると、バインドマウントのおかげで変更がほぼ即座に反映されるはずです。Nodemonは変更を検出し、サーバーを再起動します。Nodeサーバーが再起動するまでに数秒かかることがあります。エラーが発生した場合は、数秒後にリフレッシュしてみてください。

    Screenshot of updated label for Add button
  3. Feel free to make any other changes you'd like to make. Each time you make a change and save a file, the change is reflected in the container because of the bind mount. When Nodemon detects a change, it restarts the app inside the container automatically. When you're done, stop the container and build your new image using:他に変更したいことがあれば自由に行ってください。ファイルを保存するたびに変更がコンテナに反映されます。Nodemonが変更を検出すると、コンテナ内のアプリが自動的に再起動します。作業が完了したら、コンテナを停止し、新しいイメージをビルドします:

    $ docker build -t getting-started .
    

Summary概要

At this point, you can persist your database and see changes in your app as you develop without rebuilding the image.この時点で、データベースを永続化し、アプリを開発する際に変更を確認できます。イメージを再構築する必要はありません。

In addition to volume mounts and bind mounts, Docker also supports other mount types and storage drivers for handling more complex and specialized use cases.ボリュームマウントやバインドマウントに加えて、Dockerは他のマウントタイプやストレージドライバーもサポートしており、より複雑で専門的なユースケースに対応しています。

Related information:関連情報:

Next steps次のステップ

In order to prepare your app for production, you need to migrate your database from working in SQLite to something that can scale a little better. For simplicity, you'll keep using a relational database and switch your application to use MySQL. But, how should you run MySQL? How do you allow the containers to talk to each other? You'll learn about that in the next section.アプリを本番環境に準備するためには、SQLiteで動作しているデータベースを、もう少しスケールしやすいものに移行する必要があります。簡単のために、リレーショナルデータベースを引き続き使用し、アプリケーションをMySQLに切り替えます。しかし、MySQLをどのように実行すればよいのでしょうか?コンテナ同士がどのように通信できるようにするのでしょうか?それについては次のセクションで学びます。

Multi container apps