It’s now or never

IT系の技術ブログです。気になったこと、勉強したことを備忘録的にまとめて行きます。

Docker for Macを使ってみる

現状は、Vagrantを使って開発環境を構築することが多いのですが、最近はDockerを使って開発しているという話をよく聞きます。 DockerだとマシンスペックをVMほど使用しないというのがメリットの一つらしく、素早く軽量に開発環境を整えるため役立つのかな?と思い勉強したいと思います。

Dockerのインストール

公式ページからMacアプリをダウンロードすることもできますが、 今回はHomebrew経由でインストールします。

brew cask install docker
  • インストールが完了したらDocker.appを起動

スクリーンショット 2017-04-09 14.36.48.png

  • Docker appがシステムにアクセスするための許可を求められるためOKを押下してパスワードを入力

スクリーンショット 2017-04-09 14.37.21.png

  • 上記画面が表示されるようになってDockerコマンドが使えるようになっていればインストール完了です
docker --version

Docker version 1.12.3, build 6b644ec
docker run -d -p 80:80 --name webserver nginx

Dockerコンテナを起動する

hello-world

% docker run hello-world


Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://cloud.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/
  • docker run コマンドはdockerイメージからのコンテナを起動するコマンドです。
  • 上記の出力を見るとローカルにimageが存在しないときは、Docker Hubから該当するimageを探してダウンロードするようです。

nginx

% docker run -d -p 80:80 --name webserver nginx

cdea6236c8862e3768b3560034c28c41dd7534a706a1e76b30a25c763962b32c
  • 出力されているのは、コンテナの識別IDです。
  • -d: コンテナをバックグラウンドで起動する
  • -p: ポート指定、<ホストのポート>:<コンテナのポート>で割当を行う。 例: <80>:<12345> コンテナの12345ポートをホストの80ポートに割り当てる 
  • --name: コンテナに名前を割り当てる

この状態で、localhostにブラウザでアクセスするとnginxのデフォルト起動画面が確認できます。

スクリーンショット 2017-04-09 15.41.00.png

% docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                         NAMES
cdea6236c886        nginx               "nginx -g 'daemon ..."   4 minutes ago       Up 4 minutes        0.0.0.0:80->80/tcp, 443/tcp   webserver
  • docker psで現在起動中のコンテナを確認できます。

その他のDockerコマンド

イメージの一覧

  • ローカルに保存されているDocker imageを確認する
docker images

コンテナの停止

  • dockerコンテナを停止する
docker stop <name or ID>

コンテナの削除

  • dockerコンテナを削除する
  • 同じ名前のコンテナは作成できないため一度削除する必要がある
docker rm <name or ID>

参考