Use Docker ComposeDocker Composeの使用

Docker Compose is a tool that helps you define and share multi-container applications. With Compose, you can create a YAML file to define the services and with a single command, you can spin everything up or tear it all down.Docker Composeは、マルチコンテナアプリケーションを定義し、共有するのに役立つツールです。Composeを使用すると、サービスを定義するYAMLファイルを作成でき、1つのコマンドで全てを立ち上げたり、取り壊したりできます。

The big advantage of using Compose is you can define your application stack in a file, keep it at the root of your project repository (it's now version controlled), and easily enable someone else to contribute to your project. Someone would only need to clone your repository and start the app using Compose. In fact, you might see quite a few projects on GitHub/GitLab doing exactly this now.Composeを使用する大きな利点は、アプリケーションスタックをファイルで定義し、それをプロジェクトリポジトリのルートに保持できることです(これによりバージョン管理されます)。他の誰かがプロジェクトに貢献しやすくなります。誰かがあなたのリポジトリをクローンし、Composeを使用してアプリを開始するだけで済みます。実際、今ではGitHub/GitLab上でまさにこれを行っているプロジェクトがかなりあります。

Create the Compose fileComposeファイルを作成する

In the getting-started-app directory, create a file named compose.yaml.ディレクトリ getting-started-appcompose.yaml という名前のファイルを作成します。

├── getting-started-app/
│ ├── Dockerfile
│ ├── compose.yaml
│ ├── node_modules/
│ ├── package.json
│ ├── spec/
│ ├── src/
│ └── yarn.lock

Define the app serviceアプリサービスを定義する

In part 6, you used the following command to start the application service.パート6 では、アプリケーションサービスを開始するために次のコマンドを使用しました。

$ docker run -dp 127.0.0.1:3000:3000 \
  -w /app -v "$(pwd):/app" \
  --network todo-app \
  -e MYSQL_HOST=mysql \
  -e MYSQL_USER=root \
  -e MYSQL_PASSWORD=secret \
  -e MYSQL_DB=todos \
  node:lts-alpine \
  sh -c "yarn install && yarn run dev"

You'll now define this service in the compose.yaml file.これからこのサービスを compose.yaml ファイルで定義します。

  1. Open compose.yaml in a text or code editor, and start by defining the name and image of the first service (or container) you want to run as part of your application. The name will automatically become a network alias, which will be useful when defining your MySQL service.compose.yaml をテキストまたはコードエディタで開き、アプリケーションの一部として実行したい最初のサービス(またはコンテナ)の名前とイメージを定義することから始めます。 名前は自動的にネットワークエイリアスになり、MySQLサービスを定義する際に便利です。

    services:
      app:
        image: node:lts-alpine
  2. Typically, you will see command close to the image definition, although there is no requirement on ordering. Add the command to your compose.yaml file.通常、commandimage 定義の近くに見られますが、順序に関する要件はありません。compose.yaml ファイルに command を追加します。

    services:
      app:
        image: node:lts-alpine
        command: sh -c "yarn install && yarn run dev"
  3. Now migrate the -p 127.0.0.1:3000:3000 part of the command by defining the ports for the service.次に、コマンドの -p 127.0.0.1:3000:3000 部分を移行し、サービスの ports を定義します。

    services:
      app:
        image: node:lts-alpine
        command: sh -c "yarn install && yarn run dev"
        ports:
          - 127.0.0.1:3000:3000
  4. Next, migrate both the working directory (-w /app) and the volume mapping (-v "$(pwd):/app") by using the working_dir and volumes definitions.次に、作業ディレクトリ (-w /app) とボリュームマッピング (-v "$(pwd):/app") の両方を working_dirvolumes 定義を使用して移行します。

    One advantage of Docker Compose volume definitions is you can use relative paths from the current directory.Docker Composeのボリューム定義の利点の一つは、現在のディレクトリからの相対パスを使用できることです。

    services:
      app:
        image: node:lts-alpine
        command: sh -c "yarn install && yarn run dev"
        ports:
          - 127.0.0.1:3000:3000
        working_dir: /app
        volumes:
          - ./:/app
  5. Finally, you need to migrate the environment variable definitions using the environment key.最後に、environmentキーを使用して環境変数の定義を移行する必要があります。

    services:
      app:
        image: node:lts-alpine
        command: sh -c "yarn install && yarn run dev"
        ports:
          - 127.0.0.1:3000:3000
        working_dir: /app
        volumes:
          - ./:/app
        environment:
          MYSQL_HOST: mysql
          MYSQL_USER: root
          MYSQL_PASSWORD: secret
          MYSQL_DB: todos

Define the MySQL serviceMySQLサービスを定義する

Now, it's time to define the MySQL service. The command that you used for that container was the following:さて、MySQLサービスを定義する時が来ました。そのコンテナに使用したコマンドは次のとおりです:

$ docker run -d \
  --network todo-app --network-alias mysql \
  -v todo-mysql-data:/var/lib/mysql \
  -e MYSQL_ROOT_PASSWORD=secret \
  -e MYSQL_DATABASE=todos \
  mysql:8.0
  1. First define the new service and name it mysql so it automatically gets the network alias. Also specify the image to use as well.まず、新しいサービスを定義し、mysqlという名前を付けて、自動的にネットワークエイリアスを取得できるようにします。また、使用するイメージも指定してください。

    
    services:
      app:
        # The app service definition
      mysql:
        image: mysql:8.0
  2. Next, define the volume mapping. When you ran the container with docker run, Docker created the named volume automatically. However, that doesn't happen when running with Compose. You need to define the volume in the top-level volumes: section and then specify the mountpoint in the service config. By simply providing only the volume name, the default options are used.次に、ボリュームマッピングを定義します。docker runでコンテナを実行したとき、Dockerは自動的に名前付きボリュームを作成しました。しかし、Composeで実行する場合はそうなりません。最上位のvolumes:セクションでボリュームを定義し、サービス設定でマウントポイントを指定する必要があります。ボリューム名のみを提供することで、デフォルトのオプションが使用されます。

    services:
      app:
        # The app service definition
      mysql:
        image: mysql:8.0
        volumes:
          - todo-mysql-data:/var/lib/mysql
    
    volumes:
      todo-mysql-data:
  3. Finally, you need to specify the environment variables.最後に、環境変数を指定する必要があります。

    services:
      app:
        # The app service definition
      mysql:
        image: mysql:8.0
        volumes:
          - todo-mysql-data:/var/lib/mysql
        environment:
          MYSQL_ROOT_PASSWORD: secret
          MYSQL_DATABASE: todos
    
    volumes:
      todo-mysql-data:

At this point, your complete compose.yaml should look like this:この時点で、あなたの完全なcompose.yamlは次のようになります:

services:
  app:
    image: node:lts-alpine
    command: sh -c "yarn install && yarn run dev"
    ports:
      - 127.0.0.1:3000:3000
    working_dir: /app
    volumes:
      - ./:/app
    environment:
      MYSQL_HOST: mysql
      MYSQL_USER: root
      MYSQL_PASSWORD: secret
      MYSQL_DB: todos

  mysql:
    image: mysql:8.0
    volumes:
      - todo-mysql-data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: todos

volumes:
  todo-mysql-data:

Run the application stackアプリケーションスタックを実行する

Now that you have your compose.yaml file, you can start your application.これでcompose.yamlファイルができたので、アプリケーションを開始できます。

  1. Make sure no other copies of the containers are running first. Use docker ps to list the containers and docker rm -f <ids> to remove them.まず、他のコンテナのコピーが実行されていないことを確認してください。docker psを使用してコンテナをリストし、docker rm -f <ids>を使用してそれらを削除します。

  2. Start up the application stack using the docker compose up command. Add the -d flag to run everything in the background.アプリケーションスタックを docker compose up コマンドを使用して起動します。すべてをバックグラウンドで実行するには、-d フラグを追加します。

    $ docker compose up -d
    

    When you run the previous command, you should see output like the following:前のコマンドを実行すると、次のような出力が表示されるはずです:

    Creating network "app_default" with the default driver
    Creating volume "app_todo-mysql-data" with default driver
    Creating app_app_1   ... done
    Creating app_mysql_1 ... done

    You'll notice that Docker Compose created the volume as well as a network. By default, Docker Compose automatically creates a network specifically for the application stack (which is why you didn't define one in the Compose file).Docker Compose がボリュームとネットワークを作成したことに気付くでしょう。デフォルトでは、Docker Compose はアプリケーションスタック専用のネットワークを自動的に作成します(そのため、Compose ファイルでネットワークを定義しなかったのです)。

  3. Look at the logs using the docker compose logs -f command. You'll see the logs from each of the services interleaved into a single stream. This is incredibly useful when you want to watch for timing-related issues. The -f flag follows the log, so will give you live output as it's generated.docker compose logs -f コマンドを使用してログを確認します。各サービスのログが単一のストリームに交互に表示されます。これは、タイミングに関連する問題を監視したいときに非常に便利です。-f フラグはログを追跡し、生成されると同時にライブ出力を提供します。

    If you have run the command already, you'll see output that looks like this:すでにコマンドを実行している場合、次のような出力が表示されます:

    mysql_1  | 2019-10-03T03:07:16.083639Z 0 [Note] mysqld: ready for connections.
    mysql_1  | Version: '8.0.31'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
    app_1    | Connected to mysql db at host mysql
    app_1    | Listening on port 3000

    The service name is displayed at the beginning of the line (often colored) to help distinguish messages. If you want to view the logs for a specific service, you can add the service name to the end of the logs command (for example, docker compose logs -f app).サービス名は行の先頭に表示され(しばしば色付き)、メッセージを区別するのに役立ちます。特定のサービスのログを表示したい場合は、ログコマンドの末尾にサービス名を追加できます(例えば、docker compose logs -f app)。

  4. At this point, you should be able to open your app in your browser on http://localhost:3000 and see it running.この時点で、ブラウザで http://localhost:3000 を開いてアプリが実行されているのを見ることができるはずです。

See the app stack in Docker Desktop DashboardDocker Desktop ダッシュボードでアプリスタックを見る

If you look at the Docker Desktop Dashboard, you'll see that there is a group named getting-started-app. This is the project name from Docker Compose and used to group the containers together. By default, the project name is simply the name of the directory that the compose.yaml was located in.Docker Desktop ダッシュボードを見ると、getting-started-app というグループがあることがわかります。これは Docker Compose のプロジェクト名で、コンテナをグループ化するために使用されます。デフォルトでは、プロジェクト名は compose.yaml が存在するディレクトリの名前です。

If you expand the stack, you'll see the two containers you defined in the Compose file. The names are also a little more descriptive, as they follow the pattern of <service-name>-<replica-number>. So, it's very easy to quickly see what container is your app and which container is the mysql database.スタックを展開すると、Compose ファイルで定義した2つのコンテナが表示されます。名前も少し説明的で、<service-name>-<replica-number> のパターンに従っています。したがって、どのコンテナがアプリで、どのコンテナが MySQL データベースであるかをすぐに確認することができます。

Tear it all downすべてを破棄する

When you're ready to tear it all down, simply run docker compose down or hit the trash can on the Docker Desktop Dashboard for the entire app. The containers will stop and the network will be removed.すべてを破棄する準備ができたら、単に docker compose down を実行するか、Docker Desktop Dashboardのゴミ箱アイコンをクリックしてください。 アプリ全体が停止し、ネットワークが削除されます。

Warning

By default, named volumes in your compose file are not removed when you run docker compose down. If you want to remove the volumes, you need to add the --volumes flag.デフォルトでは、composeファイル内の名前付きボリュームは、docker compose down を実行しても削除されません。ボリュームを削除したい場合は、--volumes フラグを追加する必要があります。

The Docker Desktop Dashboard does not remove volumes when you delete the app stack.Docker Desktop Dashboardは、アプリスタックを削除してもボリュームを削除しません。

Summary概要

In this section, you learned about Docker Compose and how it helps you simplify the way you define and share multi-service applications.このセクションでは、Docker Composeについて学び、マルチサービスアプリケーションを定義し共有する方法を簡素化する手助けをすることを学びました。

Related information:関連情報:

Next steps次のステップ

Next, you'll learn about a few best practices you can use to improve your Dockerfile.次に、Dockerfileを改善するために使用できるいくつかのベストプラクティスについて学びます。

Image-building best practices