序章

Docker プラットフォームを使用すると、開発者はアプリケーションをcontainerとしてパッケージ化して実行できます。 コンテナは、共有オペレーティングシステム上で実行される分離されたプロセスであり、仮想マシンに代わる軽量の代替手段を提供します。 Though containers are not new, they offer a number of benefits — including process isolation and environment standardization — that are growing in importance as more developers use distributed application architectures.

Dockerを使用してアプリケーションを構築およびスケーリングする場合、開始点は通常、アプリケーションのイメージを作成し、それをコンテナーで実行できるようにすることです。 このイメージには、アプリケーションコード、ライブラリ、構成ファイル、環境変数、およびランタイムが含まれています。 イメージを使用すると、コンテナー内の環境が標準化され、アプリケーションのビルドと実行に必要なものだけが含まれるようになります。

In this tutorial, you will create an application image for a static website that uses the Express and Bootstrap frameworks. 次に、そのイメージを使用してコンテナーを作成し、将来使用するために DockerHubにプッシュします。 最後に、Docker Hubリポジトリから保存されたイメージをプルして別のコンテナーを構築し、アプリケーションを再作成してスケーリングする方法を示します。

前提条件

このチュートリアルに従うには、次のものが必要です。

  • この初期サーバーセットアップガイドに従ってセットアップされた1つのUbuntu18.04サーバー。
  • Ubuntu18.04にDockerをインストールして使用する方法の手順1と2に従ってサーバーにDockerをインストールします。
  • Node.jsとnpmがインストールされ、NodeSourceによって管理されるPPAを使用してインストールするためのこれらの手順に従います。
  • DockerHubアカウント。 これを設定する方法の概要については、DockerHubの使用を開始する際のこの紹介を参照してください。

ステップ1—アプリケーションの依存関係をインストールする

イメージを作成するには、最初にアプリケーションファイルを作成する必要があります。その後、アプリケーションファイルをコンテナにコピーできます。 これらのファイルには、アプリケーションの静的コンテンツ、コード、および依存関係が含まれます。

Create a directory for your project in your non-root user’s home directory. The directory in this example named node_project、ただし、これを他のものに自由に置き換える必要があります。

  1. mkdir node_project

このディレクトリに移動します。

  1. cd node_project

これがプロジェクトのルートディレクトリになります。

次に、プロジェクトの依存関係とその他の識別情報を使用してpackage.jsonファイルを作成します。 でファイルを開く nano またはお気に入りの編集者:

  1. nano package.json

プロジェクトの名前、作成者、ライセンス、エントリポイント、依存関係など、プロジェクトに関する次の情報を追加します。 著者情報を自分の名前と連絡先の詳細に置き換えてください。

〜/ node_project / package.json
{
  "name": "nodejs-image-demo",
  "version": "1.0.0",
  "description": "nodejs image demo",
  "author": "Sammy the Shark <[email protected]>",
  "license": "MIT",
  "main": "app.js",
  "keywords": [
    "nodejs",
    "bootstrap",
    "express"
  ],
  "dependencies": {
    "express": "^4.16.4"
  }
}

このファイルには、プロジェクト名、作成者、および共有されているライセンスが含まれています。 npm recommends making your project name short and descriptive, and avoiding duplicates in the npm registry. This example lists the MIT license in the license field, permitting the free use and distribution of the application code.

さらに、ファイルは以下を指定します。

  • "main":アプリケーションのエントリポイント、 app.js. 次に、このファイルを作成します。
  • "dependencies":プロジェクトの依存関係—この場合、Express4.16.4以降。

このファイルにはリポジトリがリストされていませんが、package.jsonファイルへのリポジトリの追加に関する次のガイドラインに従ってリポジトリを追加できます。 アプリケーションをバージョン管理している場合、これは良い追加です。

Save and close the file by typing CTRL + X. Press Y and then ENTER to confirm your changes.

プロジェクトの依存関係をインストールするには、次のコマンドを実行します。

  1. npm install

これにより、リストしたパッケージがインストールされます package.json プロジェクトディレクトリ内のファイル。

You can now move on to building the application files.

ステップ2—アプリケーションファイルを作成する

You will create a website that offers users information about sharks. This application will have a main entrypoint, app.js、および views プロジェクトの静的アセットを含むディレクトリ。 ランディングページ、 index.html、ユーザーにいくつかの予備情報と、より詳細なサメ情報を含むページへのリンクを提供します。 sharks.html. の中に views directory, you will create both the landing page and sharks.html.

まず、開く app.js プロジェクトのルートを定義するには、メインプロジェクトディレクトリで次の手順を実行します。

  1. nano app.js

In the first part of this file, create the Express application and Router objects and define the base directory and port as constants:

〜/ node_project / app.js
const express = require('express');
const app = express();
const router = express.Router();

const path = __dirname + '/views/';
const port = 8080;

The require 関数は express module, which is used to create the approuter オブジェクト。 The router object will perform the routing function of the application, and as you define HTTP method routes you will add them to this object to define how your application will handle requests.

ファイルのこのセクションには、いくつかの定数も設定されています。 pathport:

  • path:ベースディレクトリを定義します。 views 現在のプロジェクトディレクトリ内のサブディレクトリ。
  • port:アプリにリッスンしてポートにバインドするように指示します 8080.

次に、を使用してアプリケーションのルートを設定します router 物体:

〜/ node_project / app.js
...

router.use(function (req,res,next) {
  console.log('/' + req.method);
  next();
});

router.get('/', function(req,res){
  res.sendFile(path + 'index.html');
});

router.get('/sharks', function(req,res){
  res.sendFile(path + 'sharks.html');
});

The router.use 関数は、ルーターの要求をログに記録してアプリケーションのルートに渡すミドルウェア関数をロードします。 These are defined in the subsequent functions, which specify that a GET request to the base project URL should return the index.html page, while a GET request to the /sharks ルートが戻る必要があります sharks.html.

最後に、 router ミドルウェアとアプリケーションの静的アセットを使用して、ポートでリッスンするようにアプリに指示します 8080:

〜/ node_project / app.js
...

app.use(express.static(path));
app.use('/', router);

app.listen(port, function () {
  console.log('Example app listening on port 8080!')
})

完成した app.js file includes all of the following lines of code:

〜/ node_project / app.js
const express = require('express');
const app = express();
const router = express.Router();

const path = __dirname + '/views/';
const port = 8080;

router.use(function (req,res,next) {
  console.log('/' + req.method);
  next();
});

router.get('/', function(req,res){
  res.sendFile(path + 'index.html');
});

router.get('/sharks', function(req,res){
  res.sendFile(path + 'sharks.html');
});

app.use(express.static(path));
app.use('/', router);

app.listen(port, function () {
  console.log('Example app listening on port 8080!')
})

終了したら、ファイルを保存して閉じます。

Next, add some static content to the application. を作成することから始めます views ディレクトリ:

  1. mkdir views

ランディングページファイルを開き、 index.html:

  1. nano views/index.html

次のコードをファイルに追加します。これにより、Boostrapがインポートされ、ジャンボトロンコンポーネントが作成され、より詳細な情報へのリンクが追加されます。 sharks.html 情報ページ:

〜/ node_project / views / index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <title>About Sharks</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link href="css/styles.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Merriweather:400,700" rel="stylesheet" type="text/css">
</head>

<body>
    <nav class="navbar navbar-dark bg-dark navbar-static-top navbar-expand-md">
        <div class="container">
            <button type="button" class="navbar-toggler collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span>
            </button> <a class="navbar-brand" href="#">Everything Sharks</a>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav mr-auto">
                    <li class="active nav-item"><a href="/" class="nav-link">Home</a>
                    </li>
                    <li class="nav-item"><a href="/sharks" class="nav-link">Sharks</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="jumbotron">
        <div class="container">
            <h1>Want to Learn About Sharks?</h1>
            <p>Are you ready to learn about sharks?</p>
            <br>
            <p><a class="btn btn-primary btn-lg" href="/sharks" role="button">Get Shark Info</a>
            </p>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-lg-6">
                <h3>Not all sharks are alike</h3>
                <p>Though some are dangerous, sharks generally do not attack humans. Out of the 500 species known to researchers, only 30 have been known to attack humans.
                </p>
            </div>
            <div class="col-lg-6">
                <h3>Sharks are ancient</h3>
                <p>There is evidence to suggest that sharks lived up to 400 million years ago.
                </p>
            </div>
        </div>
    </div>
</body>

</html>

The following is a quick break-down of the various elements in your index.html file. The top-level navbar allows users to toggle between the Home and Sharks pages. の中に navbar-nav subcomponent, you are using Bootstrap’s active 現在のページをユーザーに示すクラス。 You’ve also specified the routes to your static pages, which match the routes you defined in app.js:

〜/ node_project / views / index.html
...
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
   <ul class="nav navbar-nav mr-auto">
      <li class="active nav-item"><a href="/" class="nav-link">Home</a>
      </li>
      <li class="nav-item"><a href="/sharks" class="nav-link">Sharks</a>
      </li>
   </ul>
</div>
...

Additionally, you’ve created a link to your shark information page in your jumbotron’s button:

〜/ node_project / views / index.html
...
<div class="jumbotron">
   <div class="container">
      <h1>Want to Learn About Sharks?</h1>
      <p>Are you ready to learn about sharks?</p>
      <br>
      <p><a class="btn btn-primary btn-lg" href="/sharks" role="button">Get Shark Info</a>
      </p>
   </div>
</div>
...

ヘッダーにはカスタムスタイルシートへのリンクもあります。

〜/ node_project / views / index.html
...
<link href="css/styles.css" rel="stylesheet">
...

You will create this style sheet at the end of this step.

終了したら、ファイルを保存して閉じます。

With the application landing page in place, you can create your shark information page, sharks.html、興味のあるユーザーにサメに関するより多くの情報を提供します。

ファイルを開きます。

  1. nano views/sharks.html

Add the following code, which imports Bootstrap, the custom style sheet, and detailed information about certain sharks:

〜/ node_project / views / sharks.html
<!DOCTYPE html>
<html lang="en">

<head>
    <title>About Sharks</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link href="css/styles.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Merriweather:400,700" rel="stylesheet" type="text/css">
</head>
<nav class="navbar navbar-dark bg-dark navbar-static-top navbar-expand-md">
    <div class="container">
        <button type="button" class="navbar-toggler collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span>
        </button> <a class="navbar-brand" href="/">Everything Sharks</a>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav mr-auto">
                <li class="nav-item"><a href="/" class="nav-link">Home</a>
                </li>
                <li class="active nav-item"><a href="/sharks" class="nav-link">Sharks</a>
                </li>
            </ul>
        </div>
    </div>
</nav>
<div class="jumbotron text-center">
    <h1>Shark Info</h1>
</div>
<div class="container">
    <div class="row">
        <div class="col-lg-6">
            <p>
                <div class="caption">Some sharks are known to be dangerous to humans, though many more are not. The sawshark, for example, is not considered a threat to humans.
                </div>
                <img src="https://assets.digitalocean.com/articles/docker_node_image/sawshark.jpg" alt="Sawshark">
            </p>
        </div>
        <div class="col-lg-6">
            <p>
                <div class="caption">Other sharks are known to be friendly and welcoming!</div>
                <img src="https://assets.digitalocean.com/articles/docker_node_image/sammy.png" alt="Sammy the Shark">
            </p>
        </div>
    </div>
</div>

</html>

Note that in this file, you once again use the active Bootstrap class to indicate the current page.

終了したら、ファイルを保存して閉じます。

最後に、にリンクしたカスタムCSSスタイルシートを作成します index.htmlsharks.html by creating a css のフォルダ views ディレクトリ:

  1. mkdir views/css

スタイルシートを開きます。

  1. nano views/css/styles.css

Add the following code, which will set the desired color and font for your pages:

〜/ node_project / views / css / styles.css
.navbar {
	margin-bottom: 0;
}

body {
	background: #020A1B;
	color: #ffffff;
	font-family: 'Merriweather', sans-serif;
}

h1,
h2 {
	font-weight: bold;
}

p {
	font-size: 16px;
	color: #ffffff;
}

.jumbotron {
	background: #0048CD;
	color: white;
	text-align: center;
}

.jumbotron p {
	color: white;
	font-size: 26px;
}

.btn-primary {
	color: #fff;
	text-color: #000000;
	border-color: white;
	margin-bottom: 5px;
}

img,
video,
audio {
	margin-top: 20px;
	max-width: 80%;
}

div.caption: {
	float: left;
	clear: both;
}

このファイルは、フォントと色の設定に加えて、を指定して画像のサイズを制限します。 max-width 80%の。 This will prevent the pictures from taking up more room than you would like on the page.

終了したら、ファイルを保存して閉じます。

アプリケーションファイルが配置され、プロジェクトの依存関係がインストールされたら、アプリケーションを起動する準備が整います。

前提条件の初期サーバーセットアップチュートリアルに従った場合、SSHトラフィックのみを許可するアクティブなファイアウォールがあります。 ポートへのトラフィックを許可するには 8080 走る:

  1. sudo ufw allow 8080

アプリケーションを起動するには、プロジェクトのルートディレクトリにいることを確認してください。

  1. cd ~/node_project

でアプリケーションを開始します node app.js:

  1. node app.js

ブラウザを次の場所に移動します http://your_server_ip:8080. The following is your landing page:

Clicking on the Get Shark Info button will take you to the following information page:

これで、アプリケーションが稼働しています。 準備ができたら、次のように入力してサーバーを終了します CTRL + C. You can now move on to creating the Dockerfile that will allow you to recreate and scale this application as desired.

ステップ3—Dockerfileを作成する

Dockerfileは、実行時にアプリケーションコンテナに含まれるものを指定します。 Dockerfileを使用すると、コンテナー環境を定義し、依存関係またはランタイムバージョンとの不一致を回避できます。

Following these guidelines on building optimized containers, will make your image as efficient as possible by minimizing the number of image layers and restricting the image’s function to a single purpose — recreating your application files and static content.

プロジェクトのルートディレクトリに、Dockerfileを作成します。

  1. nano Dockerfile

Dockerイメージは、相互に構築される一連のレイヤードイメージを使用して作成されます。 The first step will be to add the base image for your application that will form the starting point of the application build.

You can use the node:10-alpine image. The alpine image is derived from the Alpine Linux project, and will help keep your image size down. かどうかの詳細については alpine image is the right choice for your project, please see the full discussion under the Image Variants section of the Docker Hub Node image page.

以下を追加します FROM アプリケーションのベースイメージを設定するための命令:

〜/ node_project / Dockerfile
FROM node:10-alpine

このイメージには、Node.jsとnpmが含まれています。 各Dockerfileはで始まる必要があります FROM 命令。

デフォルトでは、Dockerノードイメージにはルート以外の node ユーザーが含まれており、アプリケーションコンテナをrootとして実行しないようにするために使用できます。 コンテナーをrootとして実行することを避け、コンテナー内の機能をプロセスの実行に必要なものだけに制限することをお勧めします。 したがって、 node ユーザーのホームディレクトリをアプリケーションの作業ディレクトリとして使用し、コンテナ内のユーザーとして設定します。 Docker Nodeイメージを操作する際のベストプラクティスの詳細については、このベストプラクティスガイドを参照してください。

To fine-tune the permissions on your application code in the container, create the node_modules のサブディレクトリ /home/node 一緒に app ディレクトリ。 Creating these directories will ensure that they have the correct permissions, which will be important when you create local node modules in the container with npm install. In addition to creating these directories, set ownership on them to your node user:

〜/ node_project / Dockerfile
...
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app

統合の有用性の詳細については RUN 手順については、このコンテナレイヤーの管理方法に関する説明を参照してください。

次に、アプリケーションの作業ディレクトリをに設定します /home/node/app:

〜/ node_project / Dockerfile
...
WORKDIR /home/node/app

もし WORKDIR が設定されていない場合、Dockerはデフォルトで作成するため、明示的に設定することをお勧めします。

次に、 package.jsonpackage-lock.json (npm 5以降の場合)ファイル:

〜/ node_project / Dockerfile
...
COPY package*.json ./

これを追加する COPY 実行前の指示 npm install or copying the application code allows you to take advantage of Docker’s caching mechanism. ビルドの各段階で、Dockerはその特定の命令用にキャッシュされたレイヤーがあるかどうかを確認します。 If you change the package.json, this layer will be rebuilt, but if you don’t, this instruction will allow Docker to use the existing image layer and skip reinstalling your node modules.

すべてのアプリケーションファイルが非ルートノードユーザーによって所有されていることを確認するには、 node_modules ディレクトリ、実行する前にユーザーをnodeに切り替えます npm install:

〜/ node_project / Dockerfile
...
USER node

After copying the project dependencies and switching the user, run npm install:

〜/ node_project / Dockerfile
...
RUN npm install

次に、適切な権限を持つアプリケーションコードをコンテナのアプリケーションディレクトリにコピーします。

〜/ node_project / Dockerfile
...
COPY --chown=node:node . .

これにより、アプリケーションファイルが非ルートnodeユーザーによって所有されるようになります。

最後に、ポートを公開します 8080 コンテナでアプリケーションを起動します。

〜/ node_project / Dockerfile
...
EXPOSE 8080

CMD [ "node", "app.js" ]

EXPOSE ポートを公開しませんが、代わりに、コンテナのどのポートが実行時に公開されるかを文書化する方法として機能します。 CMD runs the command to start the application — in this case, node app.js.

Note: There should only be one CMD 各Dockerfileの命令。 複数含める場合は、最後のもののみが有効になります。

Dockerfileでできることはたくさんあります。 手順の完全なリストについては、DockerのDockerfileリファレンスドキュメントを参照してください。

This is the complete Dockerfile:

〜/ node_project / Dockerfile

FROM node:10-alpine

RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app

WORKDIR /home/node/app

COPY package*.json ./

USER node

RUN npm install

COPY --chown=node:node . .

EXPOSE 8080

CMD [ "node", "app.js" ]

編集が終了したら、ファイルを保存して閉じます。

Before building the application image, add a .dockerignore file. .gitignoreファイルと同じように機能します。 .dockerignore プロジェクトディレクトリ内のどのファイルとディレクトリをコンテナにコピーしないかを指定します。

を開きます .dockerignore ファイル:

  1. nano .dockerignore

ファイル内に、ローカルノードモジュール、npmログ、Dockerfile、および .dockerignore ファイル:

〜/ node_project / .dockerignore
node_modules
npm-debug.log
Dockerfile
.dockerignore

Git を使用している場合は、 .git ディレクトリと .gitignore ファイル。

終了したら、ファイルを保存して閉じます。

これで、 dockerbuildコマンドを使用してアプリケーションイメージをビルドする準備が整いました。 を使用して -t フラグ docker build 覚えやすい名前で画像にタグを付けることができます。 Because you’re going to push the image to Docker Hub, include your Docker Hub username in the tag. You can tag the image as nodejs-image-demo、ただし、これを自分で選択した名前に自由に置き換えてください。 交換することも忘れないでください your_dockerhub_username 独自のDockerHubユーザー名を使用:

  1. docker build -t your_dockerhub_username/nodejs-image-demo .

The . ビルドコンテキストが現在のディレクトリであることを指定します。

It will take some time to build the image. 完了したら、画像を確認します。

  1. docker images
Output
REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 8 seconds ago 73MB node 10-alpine f09e7c96b6de 13 monthss ago 82.7MB

docker run を使用して、このイメージでコンテナーを作成できるようになりました。 You will include three flags with this command:

  • -p: This publishes the port on the container and maps it to a port on your host. You can use port 80 ホスト上にありますが、そのポートで別のプロセスを実行している場合は、必要に応じてこれを自由に変更する必要があります。 これがどのように機能するかについての詳細は、ポートバインディングに関するDockerドキュメントのこの説明を参照してください。
  • -d:これは、コンテナをバックグラウンドで実行します。
  • --name: This allows you to give the container a memorable name.

次のコマンドを実行して、コンテナーを作成します。

  1. docker run --name nodejs-image-demo -p 80:8080 -d your_dockerhub_username/nodejs-image-demo

コンテナーが稼働状態になったら、 dockerpsを使用して実行中のコンテナーのリストを検査できます。

  1. docker ps
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e50ad27074a7 your_dockerhub_username/nodejs-image-demo "docker-entrypoint.s…" 13 seconds ago Up 12 seconds 0.0.0.0:80->8080/tcp, :::80->8080/tcp nodejs-image-demo

コンテナが実行されている状態で、ブラウザを次の場所に移動してアプリケーションにアクセスできます。 http://your_server_ip:

アプリケーションのイメージを作成したので、将来使用するためにそれをDockerHubにプッシュできます。

ステップ4—リポジトリを使用して画像を操作する

アプリケーションイメージをDockerHubなどのレジストリにプッシュすることで、コンテナーを構築およびスケーリングするときに後で使用できるようになります。 To demonstrate how this works, you will push the application image to a repository and then use the image to recreate your container.

イメージをプッシュするための最初のステップは、前提条件で作成したDockerHubアカウントにログインすることです。

  1. docker login -u your_dockerhub_username

プロンプトが表示されたら、DockerHubアカウントのパスワードを入力します。 この方法でログインすると、 ~/.docker/config.json DockerHubのクレデンシャルを使用してユーザーのホームディレクトリにファイルします。

これで、前に作成したタグを使用して、アプリケーションイメージをDockerHubにプッシュできます。 your_dockerhub_username/nodejs-image-demo:

  1. docker push your_dockerhub_username/nodejs-image-demo

現在のアプリケーションコンテナとイメージを破棄し、リポジトリ内のイメージを使用してそれらを再構築することにより、イメージレジストリのユーティリティをテストしてみましょう。

まず、実行中のコンテナを一覧表示します。

  1. docker ps
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e50ad27074a7 your_dockerhub_username/nodejs-image-demo "docker-entrypoint.s…" 5 minutes ago Up 5 minutes 0.0.0.0:80->8080/tcp, :::80->8080/tcp nodejs-image-demo

を使用して CONTAINER ID 出力にリストされている場合は、実行中のアプリケーションコンテナを停止します。 以下で強調表示されているIDを自分のものに置き換えてください CONTAINER ID:

  1. docker stop e50ad27074a7

すべての画像を -a 国旗:

  1. docker images -a

The following is output with the name of your image, your_dockerhub_username/nodejs-image-demo、 一緒に node 画像とビルドからの他の画像:

Output
REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 7 minutes ago 73MB <none> <none> 2e3267d9ac02 4 minutes ago 72.9MB <none> <none> 8352b41730b9 4 minutes ago 73MB <none> <none> 5d58b92823cb 4 minutes ago 73MB <none> <none> 3f1e35d7062a 4 minutes ago 73MB <none> <none> 02176311e4d0 4 minutes ago 73MB <none> <none> 8e84b33edcda 4 minutes ago 70.7MB <none> <none> 6a5ed70f86f2 4 minutes ago 70.7MB <none> <none> 776b2637d3c1 4 minutes ago 70.7MB node 10-alpine f09e7c96b6de 13 months ago 82.7MB

次のコマンドを使用して、停止したコンテナと、未使用またはぶら下がっているイメージを含むすべてのイメージを削除します。

docker system prune -a

タイプ y 停止したコンテナとイメージを削除することを確認するために出力でプロンプトが表示されたら。 これにより、ビルドキャッシュも削除されることに注意してください。

これで、アプリケーションイメージを実行しているコンテナとイメージ自体の両方が削除されました。 Dockerコンテナー、イメージ、およびボリュームの削除の詳細については、 Dockerイメージ、コンテナー、およびボリュームを削除する方法を参照してください。

すべてのイメージとコンテナーが削除されたので、DockerHubからアプリケーションイメージをプルできます。

  1. docker pull your_dockerhub_username/nodejs-image-demo

画像をもう一度リストします。

  1. docker images

アプリケーションイメージが表示されます。

Output
REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 11 minutes ago 73MB

これで、ステップ3のコマンドを使用してコンテナーを再構築できます。

  1. docker run --name nodejs-image-demo -p 80:8080 -d your_dockerhub_username/nodejs-image-demo

実行中のコンテナを一覧表示します。

  1. docker ps
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f6bc2f50dff6 your_dockerhub_username/nodejs-image-demo "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 0.0.0.0:80->8080/tcp, :::80->8080/tcp nodejs-image-demo

訪問 http://your_server_ip もう一度、実行中のアプリケーションを表示します。

結論

このチュートリアルでは、ExpressとBootstrapを使用して静的Webアプリケーションを作成し、このアプリケーションのDockerイメージを作成しました。 このイメージを使用してコンテナーを作成し、イメージをDockerHubにプッシュしました。 そこから、イメージとコンテナーを破棄し、DockerHubリポジトリを使用してそれらを再作成することができました。

DockerComposeやDockerMachineなどのツールを使用してマルチコンテナーセットアップを作成する方法について詳しく知りたい場合は、次のガイドを参照してください。

  • Ubuntu18.04にDockerComposeをインストールする方法。
  • Ubuntu18.04でDockerマシンを使用してリモートDockerホストをプロビジョニングおよび管理する方法。

コンテナデータの操作に関する一般的なヒントについては、以下を参照してください。

他のDocker関連のトピックに興味がある場合は、Dockerチュートリアルの完全なライブラリを参照してください。