2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

簡単な Dockerfile を作成してコンテナを立ち上げる

Last updated at Posted at 2021-09-16

はじめに

簡単な Dockerfile を作ってコンテナを立ち上げる をします。

準備

shell
# Dockerfile 作成
$ touch Dockerfile

# Dockerfile 編集
$ vi Dockerfile

# vi 操作
# i を押して インサートモード
# 下記 Dockerfile の内容をコピーペースト
# ペーストしたら esc でコマンドモード
# :wq と入力しエンター で保存して終了

$ touch index.php
$ vi index.php
# Dockerfileの時と同様に、 vi 操作でコピーペースト

下記2つのファイルが作成できればOK

Dockerfile
# FROM で元となるイメージの指定
FROM php:apache
# Dockerfileが存在するディレクトリの内容を、 イメージのファイルシステム上のパス /var/www/html/ にコピー
COPY . /var/www/html/
index.php
<?php
// phpinfo — PHP の設定情報を出力する
phpinfo();
?>

イメージのビルド

先程作成した Dockerfile が存在するディレクトリで実行

shell
# -t で ビルドするイメージに php-test という名前をつける
# . は 元になるDockerfileの位置を指定
$ docker build -t php-test .

# イメージ一覧表示
$ docker image ls
REPOSITORY   TAG       IMAGE ID       CREATED              SIZE
php-test     latest    9261467f1c80   About a minute ago   473MB

# ↑php-test という名前のイメージがあればOK!

コンテナ作成

shell
# -d (デタッチド) コンテナをバックグラウンドで起動
# -p 80:80 (ポートフォワード) localhost の80番ポート にアクセスが来たら コンテナ の80番ポートに繋ぐ
# --name (コンテナ名) コンテナ名を php-test-container にする
# php-test イメージを元にコンテナを作成する
$ docker run -d -p 80:80 --name php-test-container php-test

# 起動しているコンテナを一覧表示
$ docker container ls
# 一部項目省略 
CONTAINER ID   IMAGE      CREATED         STATUS         PORTS                NAMES
08020b5a1b50   php-test   6 seconds ago   Up 5 seconds   0.0.0.0:80->80/tcp   php-test-container

# コンテナが立ち上がったので localhost を開く
$ open http://localhost 

下記画像のような画面が表示されれば成功!

スクリーンショット 2021-09-16 19.30.40.png

Dockerfile内の COPY について補足

shell
# コンテナ内のshell(bash)を起動し操作できるようにする
$ docker exec -it php-test-container bash

# root@[コンテナIDの一部]:[イメージのファイルシステム上のパス] 
root@b41c68711750:/var/www/html# ls
# Dockerfileに記載した COPY . /var/www/html/ でcopyされた Dokerfile と index.php が表示される 
Dockerfile  index.php 

# コンテナ内のshellから抜ける
root@b41c68711750:/var/www/html# exit

片付け

shell
# コンテナ停止
$ docker stop php-test-container
php-test-container # コンテナ名表示されれば成功

# コンテナ削除
$ docker rm php-test-container                             
php-test-container # コンテナ名表示されれば成功

# イメージ削除
$ docker rmi php-test       
Untagged: php-test:latest
Deleted: sha256:7103bbe5f77b40234a9b8791b1ab3383c8e0fc1a9fc8489bb40922177753c4a6 # deleted 表示で成功

まとめ

簡単なDockerfileを作成してコンテナを立ち上げる をしました!

2
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?