如何使用Docker构建Node.js应用程序[快速入门]

本教程指导您创建使用Express和Bootstrap的静态网站的Docker映像。从安装依赖项开始,然后创建应用文件,编写Dockerfile,将镜像推送到Docker Hub,并重建应用容器,展示如何通过Docker实现应用的可复制和扩展。
摘要由CSDN通过智能技术生成

介绍 (Introduction)

This tutorial will walk you through creating an application image for a static website that uses the Express framework and Bootstrap. You will then build a container using that image, push it to Docker Hub, and use it to build another container, demonstrating how you can recreate and scale your application.

本教程将引导您为使用Express框架和Bootstrap的静态网站创建应用程序映像。 然后,您将使用该映像构建一个容器,将其推送到Docker Hub ,并使用它构建另一个容器,演示如何重新创建和扩展应用程序。

For a more detailed version of this tutorial, with more detailed explanations of each step, please refer to How To Build a Node.js Application with Docker.

有关本教程的更详细版本,以及每个步骤的更详细说明,请参阅如何使用Docker构建Node.js应用程序

先决条件 (Prerequisites)

To follow this tutorial, you will need:

要遵循本教程,您将需要:

  • A sudo user on your server or in your local environment.

    服务器或本地环境中的sudo用户。

  • Docker.

    码头工人
  • Node.js and npm.

    Node.js和npm

  • A Docker Hub account.

    Docker Hub帐户。

第1步-安装应用程序依赖项 (Step 1 — Installing Your Application Dependencies)

First, create a directory for your project in your non-root user’s home directory:

首先,在非root用户的主目录中为您的项目创建一个目录:

  • mkdir node_project

    mkdir node_project

Navigate to this directory:

导航到此目录:

  • cd node_project

    cd node_project

This will be the root directory of the project.

这将是项目的根目录。

Next, create a package.json with your project’s dependencies:

接下来,使用项目的依赖项创建package.json

  • nano package.json

    纳米package.json

Add the following information about the project to the file; be sure to replace the author information with your own name and contact details:

将有关项目的以下信息添加到文件中; 请务必用您自己的姓名和联系方式替换作者信息:

~/node_project/package.json
〜/ node_project / package.json
{
  "name": "nodejs-image-demo",
  "version": "1.0.0",
  "description": "nodejs image demo",
  "author": "Sammy the Shark <sammy@example.com>",
  "license": "MIT",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "bootstrap",
    "express"
  ],
  "dependencies": {
    "express": "^4.16.4"
  }
}

Install your project’s dependencies:

安装项目的依赖项:

  • npm install

    npm安装

第2步-创建应用程序文件 (Step 2 — Creating the Application Files)

We will create a website that offers users information about sharks.

我们将创建一个网站,向用户提供有关鲨鱼的信息。

Open app.js in the main project directory to define the project’s routes:

在主项目目录中打开app.js ,以定义项目的路线:

  • nano app.js

    纳米app.js

Add the following content to the file to create the Express application and Router objects, define the base directory, port, and host as variables, set the routes, and mount the router middleware along with the application’s static assets:

将以下内容添加到文件中以创建Express应用程序和Router对象,将基本目录,端口和主机定义为变量,设置路由,并将router中间件与应用程序的静态资产一起安装:

~/node_project/app.js
〜/ node_project / app.js
var express = require("express");
var app = express();
var router = express.Router();

var path = __dirname + '/views/';

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

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(8080, function () {
  console.log('Example app listening on port 8080!')
})

Next, let’s add some static content to the application. Create the views directory:

接下来,让我们向应用程序中添加一些静态内容。 创建views目录:

  • mkdir views

    mkdir视图

Open index.html:

打开index.html

  • nano views/index.html

    nano views / index.html

Add the following code to the file, which will import Boostrap and create a jumbotron component with a link to the more detailed sharks.html info page:

将以下代码添加到该文件中,该文件将导入Boostrap并创建一个jumbotron组件,并带有指向更详细的sharks.html信息页面的链接:

~/node_project/views/index.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://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <link href="css/styles.css" rel="stylesheet">
      <link href='https://fonts.googleapis.com/css?family=Merriweather:400,700' rel='stylesheet' type='text/css'>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>
      <nav class="navbar navbar-inverse navbar-static-top">
         <div class="container">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <a class="navbar-brand" href="#">Everything Sharks</a>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav mr-auto">
                  <li class="active"><a href="/">Home</a></li>
                  <li><a href="/sharks">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-md-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-md-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>

Next, open a file called sharks.html:

接下来,打开一个名为sharks.html的文件:

  • nano views/sharks.html

    nano views / sharks.html

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

添加以下代码,这些代码将导入Bootstrap和自定义样式表,并向用户提供有关某些鲨鱼的详细信息:

~/node_project/views/sharks.html
〜/ 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://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <link href="css/styles.css" rel="stylesheet">
      <link href='https://fonts.googleapis.com/css?family=Merriweather:400,700' rel='stylesheet' type='text/css'>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <nav class="navbar navbar-inverse navbar-static-top">
      <div class="container">
         <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Everything Sharks</a>
         </div>
         <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav mr-auto">
               <li><a href="/">Home</a></li>
               <li class="active"><a href="/sharks">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-md-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-md-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>
   </body>
</html>

Finally, create the custom CSS style sheet that you’ve linked to in index.html and sharks.html by first creating a css folder in the views directory:

最后,首先在views目录中创建一个css文件夹,以创建已在index.htmlsharks.html链接到的自定义CSS样式表:

  • mkdir views/css

    mkdir视图/ css

Open the style sheet and add the following code, which will set the desired color and font for our pages:

打开样式表并添加以下代码,这将为我们的页面设置所需的颜色和字体:

~/node_project/views/css/styles.css
〜/ 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;
}

Start the application:

启动应用程序:

  • npm start

    npm开始

Navigate your browser to http://your_server_ip:8080 or localhost:8080 if you are working locally. You will see the following landing page:

如果您在本地工作,请将浏览器导航到http:// your_server_ip :8080localhost:8080 。 您将看到以下登录页面:

Click on the Get Shark Info button. You will see the following information page:

单击获取鲨鱼信息按钮。 您将看到以下信息页面:

You now have an application up and running. When you are ready, quit the server by typing CTRL+C.

现在,您已启动并运行了一个应用程序。 准备就绪后,通过键入CTRL+C退出服务器。

第3步—编写Dockerfile (Step 3 — Writing the Dockerfile)

In your project’s root directory, create the Dockerfile:

在项目的根目录中,创建Dockerfile:

  • nano Dockerfile

    纳米Dockerfile

Add the following code to the file:

将以下代码添加到文件中:

~/node_project/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" ]

This Dockerfile uses an alpine base image and ensures that application files are owned by the non-root node user that is provided by default by the Docker Node image.

该Dockerfile使用高山基础映像,并确保应用程序文件由Docker Node映像默认提供的非根节点用户拥有。

Next, add your local node modules, npm logs, Dockerfile, and .dockerignore to your .dockerignore file:

接下来,将本地节点模块,npm日志,Dockerfile和.dockerignore.dockerignore文件:

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

Build the application image using the docker build command:

使用docker build命令构建应用程序映像:

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

    docker build -t your_dockerhub_username / nodejs-image-demo 。

The . specifies that the build context is the current directory.

. 指定构建上下文是当前目录。

Check your images:

检查图像:

  • docker images

    码头工人图像

You will see the following output:

您将看到以下输出:


   
   
Output
REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 8 seconds ago 895MB node 10 f09e7c96b6de 17 hours ago 893MB

Run the following command to build a container using this image:

运行以下命令以使用此映像构建容器:

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

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

Inspect the list of your running containers with docker ps:

使用docker ps检查正在运行的容器的列表:

  • docker ps

    码头工人ps

You will see the following output:

您将看到以下输出:


   
   
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e50ad27074a7 your_dockerhub_username/nodejs-image-demo "npm start" 8 seconds ago Up 7 seconds 0.0.0.0:80->8080/tcp nodejs-image-demo

With your container running, you can now visit your application by navigating your browser to http://your_server_ip or localhost. You will see your application landing page once again:

随着容器的运行,您现在可以通过将浏览器导航到http:// your_server_iplocalhost来访问您的应用程序。 您将再次看到您的应用程序登录页面:

Now that you have created an image for your application, you can push it to Docker Hub for future use.

现在,您已经为应用程序创建了映像,您可以将其推送到Docker Hub以供将来使用。

步骤4 —使用存储库处理图像 (Step 4 — Using a Repository to Work with Images)

The first step to pushing the image is to log in to the your Docker Hub account:

推送映像的第一步是登录到您的Docker Hub帐户:

  • docker login -u your_dockerhub_username -p your_dockerhub_password

    docker登录-u your_dockerhub_username -p your_dockerhub_password

Logging in this way will create a ~/.docker/config.json file in your user’s home directory with your Docker Hub credentials.

以这种方式登录将使用Docker Hub凭据在用户的主目录中创建~/.docker/config.json文件。

Push your image up using your own username in place of your_dockerhub_username:

使用您自己的用户名代替your_dockerhub_username来推送图像:

  • docker push your_dockerhub_username/nodejs-image-demo

    docker push your_dockerhub_username / nodejs-image-demo

If you would like, you can test the utility of the image registry by destroying your current application container and image and rebuilding them.

如果您愿意,可以通过销毁当前的应用程序容器和图像并重建它们来测试图像注册表的实用程序。

First, list your running containers:

首先,列出您正在运行的容器:

  • docker ps

    码头工人ps

You will see the following output:

您将看到以下输出:


   
   
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e50ad27074a7 your_dockerhub_username/nodejs-image-demo "npm start" 3 minutes ago Up 3 minutes 0.0.0.0:80->8080/tcp nodejs-image-demo

Using the CONTAINER ID listed in your output, stop the running application container. Be sure to replace the highlighted ID below with your own CONTAINER ID:

使用输出中列出的CONTAINER ID ,停止正在运行的应用程序容器。 请务必将下面突出显示的ID替换为您自己的CONTAINER ID

  • docker stop e50ad27074a7

    码头工人停止e50ad27074a7

List your all of your images with the -a flag:

使用-a标志列出所有图像:

  • docker images -a

    码头工人图像-a

You will see the following output with the name of your image, your_dockerhub_username/nodejs-image-demo, along with the node image and the other images from your build:

您将看到以下输出,其中包含映像名称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 895MB <none> <none> e039d1b9a6a0 7 minutes ago 895MB <none> <none> dfa98908c5d1 7 minutes ago 895MB <none> <none> b9a714435a86 7 minutes ago 895MB <none> <none> 51de3ed7e944 7 minutes ago 895MB <none> <none> 5228d6c3b480 7 minutes ago 895MB <none> <none> 833b622e5492 8 minutes ago 893MB <none> <none> 5c47cc4725f1 8 minutes ago 893MB <none> <none> 5386324d89fb 8 minutes ago 893MB <none> <none> 631661025e2d 8 minutes ago 893MB node 10 f09e7c96b6de 17 hours ago 893MB

Remove the stopped container and all of the images, including unused or dangling images, with the following command:

使用以下命令删除停止的容器和所有图像,包括未使用或悬空的图像:

  • docker system prune -a

    码头工人系统修剪-a

With all of your images and containers deleted, you can now pull the application image from Docker Hub:

删除所有映像和容器后,您现在可以从Docker Hub中提取应用程序映像:

  • docker pull your_dockerhub_username/nodejs-image-demo

    docker pull your_dockerhub_username / nodejs-image-demo

List your images once again:

再次列出您的图片:

  • docker images

    码头工人图像

You will see your application image:

您将看到您的应用程序图像:


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

You can now rebuild your container using the command from Step 3:

现在,您可以使用第3步中的命令来重建容器:

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

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

List your running containers:

列出您正在运行的容器:

  • docker ps

    码头工人ps

   
   
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f6bc2f50dff6 your_dockerhub_username/nodejs-image-demo "npm start" 4 seconds ago Up 3 seconds 0.0.0.0:80->8080/tcp nodejs-image-demo

Visit http://your_server_ip or localhost once again to view your running application.

再次访问http:// your_server_iplocalhost以查看正在运行的应用程序。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-a-node-js-application-with-docker-quickstart

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值