LoginSignup
2
1

More than 1 year has passed since last update.

【Docker】基本的なdockerコマンド

Last updated at Posted at 2023-02-07

はじめに

Railsなどを中心に勉強中のエンジニア初心者が他の記事を参考にしたり、実際に実装してみたりして、アウトプットの一環としてまとめたものです。
間違っていることもあると思われるので、その際は指摘いただけると幸いです。

コンテナを起動するまでの流れ

  1. docker hubからimagepullしてきてコンテナを起動する
  2. Dockerfileをからimageをビルドして、そのimageからコンテナを起動する

docker imageを更新する流れ

  1. Dockerfileを更新して新しくimageをビルドする
  2. コンテナを更新して、それを基にimageを作成する

docker pull

docker hubからdocker imageをホスト側にpullする事ができる。

<image>:<tag>という形式でtagを指定することで、どのバージョンをpullするか指定する事ができる。指定しない場合は最新版のlatestpullされる。

$ docker pull <image>:<tag>

$ docker pull hello-world

	>
	Using default tag: latest
	latest: Pulling from library/hello-world
	Digest: sha256:faa03e786c97f07ef34423fccceeec2398ec8a5759259f94d99078f264e9d7af
	Status: Image is up to date for hello-world:latest
	docker.io/library/hello-world:latest

docker images

ホスト上にあるdocker imageのリストを確認する事ができる。

repositorydocker hubのどのrepositoryから取得したかを表している。tagdocker imageのバージョン。

$ docker images

	>
	REPOSITORY             TAG       IMAGE ID       CREATED         SIZE
	hello-world            latest    46331d942d63   8 months ago    9.14kB

docker build <build contexts>

dockerfileを基にしてdocker imageを作成する

$ docker build

docker run

指定したimageを基にしてコンテナを起動する。

imageがホスト上に存在しない場合は、docker hubから自動でpullして実行される。

コンテナは必ずしも起動し続ける必要はなく、起動した直後にテストプログラムを実行して自動で終了するなどの使い方もある。

$ docker run <image>

$ 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.
	    (arm64v8)
	 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://hub.docker.com/
	
	For more examples and ideas, visit:
	 https://docs.docker.com/get-started/

$ docker ps

	>
	CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# コンテナが起動され、コンテナ内にあるプログラムが動いた後にコンテナが終了している状態。

docker run <image> <command>

コンテナ起動後に実行するコマンドを指定することができる。

例えば、<command>に対してbashという引数を渡すと、「bash」というプログラムを実行するように命令できる。

引数がない場合はデフォルトで指定されているプログラムが実行される。

$ docker run -it ubuntu bash

	>
	root@cacb83882717:/#

	# -itはbash起動時に必要なオプション
	# root@cacb83882717は「rootユーザー」と「コンテナID」を示している

	root@cacb83882717:/ ls

		>
		bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

# コンテナ内のディレクトリ一覧が表示されている(ホスト側ではない)

$ docker ps -a

	CONTAINER ID   IMAGE          COMMAND    CREATED          STATUS                      PORTS     NAMES
	cacb83882717   ubuntu         "bash"     16 minutes ago   Exited (0) 34 seconds ago             vigilant_lalande
	ecad7969760a   hello-world    "/hello"   39 minutes ago   Exited (0) 39 minutes ago             flamboyant_franklin

# COMMANDに記載しれているコマンドがコンテナ起動後に実行されるコマンドである

docker ps

ホストの中に存在しているコンテナや、コンテナの状態について一覧で表示する。psprocess statusの略。

docker psのみだとアクティブ(起動中)なコンテナのみを表示する。

全てのコンテナ(停止中のコンテナなど)を表示するには-aオプションをつける必要がある。

$ docker ps

	>
	CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

$ docker ps -a

	>
	CONTAINER ID   IMAGE          COMMAND    CREATED         STATUS                     PORTS     NAMES
	ecad7969760a   hello-world    "/hello"   3 minutes ago   Exited (0) 3 minutes ago             flamboyant_franklin

docker restart <container>

restartコマンドでexited状態のコンテナを再度起動する事ができる。

$ docker run -it ubuntu bash

	root@cacb83882717:/ ls

		>
		bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

	root@cacb83882717:/ exit

$ docker ps -a

	>
	CONTAINER ID   IMAGE          COMMAND    CREATED          STATUS                      PORTS     NAMES
	cacb83882717   ubuntu         "bash"     16 minutes ago   Exited (0) 34 seconds ago             vigilant_lalande

$ docker restart cacb83882717

	>
	cacb83882717

$ docker ps -a

	>
	CONTAINER ID   IMAGE          COMMAND    CREATED          STATUS                      PORTS     NAMES
	cacb83882717   ubuntu         "bash"     29 minutes ago   Up 35 seconds                         vigilant_lalande

docker exec <container> <command>

指定した起動中のコンテナに対してコマンドを実行することができる。

execコマンドはexited状態のコンテナに対してはエラーになるため注意。

execexecute(実行する)の略

docker run -it <image> <command>は、imageからコンテナを作成・起動後に、そのコンテナの中でコマンドを実行している

$ docker exec -it cacb83882717 bash

	>
	root@cacb83882717:/

exitdetachでコンテナから出る

exitはコンテナを出る際に、プロセスを切ってコンテナから出る。コンテナはexited状態になる。

detachはコンテナを出る際に、プロセスを残したままコンテナから出る。コンテナはup状態のままである。

# コンテナから出て、コンテナexited状態になる
root@cacb83882717:/ exit

# コンテナから出るが、コンテナはup状態のままである
root@cacb83882717:/ ctrl+p+q

docker attach <container>で元のプロセスに戻る

detachでコンテナから出た場合、attachでコンテナに入ることで元のプロセスに戻る事ができる。

$ docker attach <container>

docker commit <container> <new container>:<tag>

編集したコンテナをimageとして保存する。

コンテナを立ち上げた後に、パッケージなどをインストールしてアプリケーションの実行環境を構築する流れが一般的である。

環境が構築出来たら、docker imageに変換(commit)してdocker hubpushすることで、他の開発メンバーに共有する事ができる。

$ docker commit cacb83882717 ubuntu:updated

	>
	sha256:1924025ed965355d25e1709e01259bbc4f2bb4fdaa4d3f8de034d0dfcb808ae3

$ docker images

	>
	REPOSITORY             TAG       IMAGE ID       CREATED         SIZE
	ubuntu                 updated   1924025ed965   2 minutes ago   69.2MB
	ubuntu                 latest    3c2df5585507   5 weeks ago     69.2MB

docker hubrepository名について

image名docker hub上のrepository名に合わせる必要があり、docker hubpushする際にimage名repository名が一致していないといけない。

docker tag <source> <target>

image名を変更する。

docker hubpushするためにはrepository名にimage名を合わせるため、ホスト上のimage名を変更する必要がある。

$ docker tag <image>:<tag> <username>/<repository>

$ docker tag ubuntu:updated xxx/my-first-repo
$ docker images

	>
	REPOSITORY                TAG       IMAGE ID       CREATED         SIZE
	ubuntu                    updated   1924025ed965   10 hours ago    69.2MB
	xxx/my-first-repo   latest    1924025ed965   10 hours ago    69.2MB

# 新しく作ったrepository名のImageIDと元のrepository名のImageIDは同じである点に注意

docker push <image>

指定したimagedocker hubpushする。

ホスト上のimagedocker hubpushした際、docker hubに元々存在しているImage Layer部分に関してはpushされずにdocker hubImage Layerを参照することになる。

$ docker push xxx/my-first-repo

	>
	Using default tag: latest
	The push refers to repository [docker.io/xxx/my-first-repo]
	4d9425067bcf: Pushed 
	12dae9600498: Mounted from library/ubuntu 
	latest: digest: sha256:5c7c539a3733d311de4fdd86654410f16acd13ea07b51afed43a4d68efc80feb size: 736

# 「4d9425067bcf」のImage Layerのみがpushされている(ubuntuのimage自体は元々docker hubにあるため)

docker rmi <image>

指定したimageを削除する。

$ docker rmi xxx/my-first-repo

	>
	Untagged: xxx/my-first-repo:latest
	Untagged: xxx/my-first-repo@sha256:5c7c539a3733d311de4fdd86654410f16acd13ea07b51afed43a4d68efc80feb

$ docker images

	>
	REPOSITORY             TAG       IMAGE ID       CREATED         SIZE
	ubuntu                 updated   1924025ed965   11 hours ago    69.2MB

docker run = (docker pull + ) docker create + docker start

docker runコマンドはdocker createimageからコンテナを作成した後に、docker startでコンテナを起動している。

$ 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.
	    (arm64v8)
	 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://hub.docker.com/
	
	For more examples and ideas, visit:
	 https://docs.docker.com/get-started/

docker create <image>

指定したimageを基にコンテナを作るが、実行はされない。状態はcreatedとなる。

$ docker create hello-world

	>
	36bfd5179428f117aa984cf2849ae09ebbbbb20569a3ece4b7d605c4449b1017

$ docker ps -a

	>
	CONTAINER ID   IMAGE          COMMAND    CREATED          STATUS                      PORTS     NAMES
	36bfd5179428   hello-world    "/hello"   22 seconds ago   Created                               dreamy_colden

docker start <container>

指定したコンテナを起動する。

コマンドを実行するとコンテナが起動され、デフォルトで設定されているプログラムが実行される、コンテナが終了する。

ただし、プログラムの実行結果は確認できない(-aオプションを付けてコンテナを実行した場合は確認できる)。

$ docker start 36bfd5179428

	>
	36bfd5179428

$ docker start 36bfd5179428 -a

	>
	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.
	    (arm64v8)
	 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://hub.docker.com/
	
	For more examples and ideas, visit:
	 https://docs.docker.com/get-started/

docker run -it ubuntu bash-itについて

-it-i-tという2つのオプションが重なって表現されている。それぞれ別々に記載してもOK。

  • -iはホストからコンテナへの入力チャネルを開くオプション(STDINをホストからコンテナに繋げる役割)。

    LinuxにはSTDIN(キーボードからの入力)STDOUTSTDERR(ディスプレイへの表示)という3つのチャネルが存在して、ホスト側とやりとりしている。

  • -tは出力結果を綺麗に表示する。

$ docker run -i -t ubuntu bash

# 上記の表現でもOK

$ docker run -t ubuntu bash

	>
	root@7f3af913d488:/ ls

	# lsを実行しても入力チャネルが開いていないためコンテナに認識されず、何も返却されない

% docker run -i ubuntu bash

	>
	ls
	bin
	boot
	dev
	etc
	home
	lib
	media
	mnt
	opt
	proc
	root
	run
	sbin
	srv
	sys
	tmp
	usr
	var

	# 綺麗に表示されない

docker remove <container>

exited状態のコンテナを削除する事ができる。

起動中のコンテナは削除できないため、停止してから削除する必要がある。

# 停止中のコンテナを削除

$ docker ps -a

	>
	CONTAINER ID   IMAGE         COMMAND    CREATED              STATUS                          PORTS     NAMES
	257be8df754a   ubuntu        "bash"     46 seconds ago       Up 45 seconds                             ecstatic_lovelace
	03b3bd8f25eb   hello-world   "/hello"   About a minute ago   Exited (0) About a minute ago             compassionate_curie

$ docker rm 03b3bd8f25eb

	>
	03b3bd8f25eb

$ docker ps -a

	>
	CONTAINER ID   IMAGE         COMMAND   CREATED              STATUS                     PORTS     NAMES
	257be8df754a   ubuntu        "bash"    About a minute ago   Up About a minute                    ecstatic_lovelace

# スペースを空けてコンテナ名を繋げることで複数のコンテナを同時に削除できる

$ docker rm <container> <container> <container>
# 起動中のコンテナを削除(エラーになる)

$ docker rm 257be8df754a

	>
	Error response from daemon:
	You cannot remove a running container 257be8df754aa7b5cd32620403303c867a25ec3db725daeb6e591bee1c3e63ea.
	Stop the container before attempting removal or force remove

docker stop <container>

起動中のコンテナを停止する。

# 起動中のコンテナを停止する

$ docker ps -a

	>
	CONTAINER ID   IMAGE         COMMAND   CREATED              STATUS                     PORTS     NAMES
	257be8df754a   ubuntu        "bash"    About a minute ago   Up About a minute                    ecstatic_lovelace

$ docker stop 257be8df754a

	>
	257be8df754a

$ docker ps -a

	>
	CONTAINER ID   IMAGE         COMMAND   CREATED          STATUS                       PORTS     NAMES
	257be8df754a   ubuntu        "bash"    8 minutes ago    Exited (137) 3 seconds ago             ecstatic_lovelace

# スペースを空けてコンテナ名を繋げることで複数のコンテナを同時に停止できる

$ docker stop <container> <container> <container>

docker system prune

停止中の全てのコンテナを削除する。Volumeなども消えるので注意。

# 起動中のコンテナを停止する

$ docker system prune

	>
	WARNING! This will remove:

		# 下記の情報が削除される
		
	  - all stopped containers
	  - all networks not used by at least one container
	  - all dangling images
	  - all dangling build cache
	
	Are you sure you want to continue? [y/N] y
	
	Deleted Containers:
	257be8df754aa7b5cd32620403303c867a25ec3db725daeb6e591bee1c3e63ea
	d343fe39ac7d55f9c88eb1acbb1d132636340901522a73eebbea9135d0de266f
	
	Deleted Networks:
	wordpress_default
	
	Deleted Images:
	deleted: sha256:0caff4dd47d5a4aa7633502a75bb2b35f19cc04f6288de0e85bb7cd06898dd1c
	deleted: sha256:f42214ebdfe5e2472fc3f9144b1a0b5dece4cead6d453e09bdb446a73681e8fe
	
	Deleted build cache objects:
	t9b1vqxdq0ap4quncgdeelmeg
	ozp3h3o7v51hytty7k9pquz7q

	Total reclaimed space: 446.4MB

docker run --name <name> <image>

コンテナに名前をつけることができる(同じ名前のコンテナを作ることはできないため注意)。

起動させ続けるコンテナを立てるときや、共有サーバを使うときなどには名前を付けると良い。

プログラムからコンテナを呼び出すときにコンテナ名が定義されていると扱いやすい(名前がない場合はコンテナのID(ランダム値)を使うことになる)。

$ docker run --name sample_container ubuntu

$ docker ps -a

	>
	CONTAINER ID   IMAGE     COMMAND   CREATED         STATUS                     PORTS     NAMES
	713db736683d   ubuntu    "bash"    8 seconds ago   Exited (0) 7 seconds ago             sample_container

detached modeforeground mode

detached modeはコンテナを起動した後にすぐdetachしてホストに戻ること(コンテナをバックグラウンドで動かす)。

  • -dオプションをつけるとdetached modeになる。
  • -dオプションを付けない場合はforeground modeとして起動される。
# バックグラウンドでコンテナを動かす場合

$ docker run -d <image>

docker run --rm <image>

--rmオプションを付けてコンテナを起動すると、Exit後にそのコンテナを自動で削除する(1回きりのコンテナとなる)

$ docker run --rm <image>
2
1
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
2
1