LoginSignup
0
0

More than 3 years have passed since last update.

Docckerfileを使ってimageを作成する方法

Last updated at Posted at 2019-06-23

今回は例としてnodejsのスクリプトを実行するイメージを作成したいと思います。

まずは、実行時のコマンドの紹介

イメージの生成

dockerfileを用いてdocker imageのbuild
(dockerfileにはあらかじめベースイメージやコマンドなどを書いておく)

$docker build -t 生成するイメージ名(:タグ名) dockerfileの場所(絶対パスor相対パス)
e.g) $ docker build -t sample .

これで、dockerfileファイルからsampleというイメージが作成される

作成したイメージの実行

$docker run --rm -it image名
e.g)$ docker run --rm -it sample

イメージの生成=>実行をワンライナーで

これをワンラーナーでやるには

$docker run --rm -it $(docker build -q .)

--rm は実行した後にimageを削除してくれるオプションです。

nodeを実行するサンプル

コードはこちら
「ローカルマシンにnodeを入れたくないけど、このサンプルコードだけは動かしたい!」みたいなとき。
まずは、node_ondockerという親ディレクトリを作成し、
その中にDockerfileと、実行したいスクリプトを格納するディレクトリnodeを作成します。

$mkdir node_ondocker
$cd node_ondocker
$touch Dockerfile
$mkdir node && touch node/test.js

Dockerfileを編集します。

Dockerfile
#「node:10.13-alpine」というイメージを取得します
FROM node:10.13-alpine
#ホストのディレクトリをコピー
COPY ["node","/node"]
#先ほどコピーしたディレクトリで次のCMDコマンドを実行したいので作業ディレクトリを/nodeに移動します
WORKDIR /node
#$node test.js というコマンドを実行します。
CMD ["node","test.js"]

このDockerfileは、
「node:10.13-alpine」というイメージを取得します

test.jsこんな感じ

test.js
console.log("hello world");

そして、以下のコマンドを打つと、test.jsの中身が実行されます!

$docker run --rm -it $(docker build -q .)
0
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
0
0