Dockerizing a Node.js web app
2019独角兽企业重金招聘Python工程师标准>>>
Dockerizing a Node.js web app
The goal of this example is to show you how to get a Node.js application into a Docker container. The guide is intended for development, and not for a production deployment. The guide also assumes you have a working Docker installation and a basic understanding of how a Node.js application is structured.
In the first part of this guide we will create a simple web application in Node.js, then we will build a Docker image for that application, and lastly we will run the image as a container.
Docker allows you to package an application with all of its dependencies into a standardized unit, called a container, for software development. A container is a stripped-to-basics version of a Linux operating system. An image is software you load into a container.
Create the Node.js app
First, create a new directory where all the files would live. In this directory create a package.json
file that describes your app and its dependencies:
{"name": "docker_web_app","version": "1.0.0","description": "Node.js on Docker","author": "First Last <first.last@example.com>","main": "server.js","scripts": {"start": "node server.js"},"dependencies": {"express": "^4.16.1"}
}
With your new package.json
file, run npm install
. If you are using npm
version 5 or later, this will generate a package-lock.json
file which will be copied to your Docker image.
Then, create a server.js
file that defines a web app using the Express.js framework:
'use strict';const express = require('express');// Constants
const PORT = 8080;
const HOST = '0.0.0.0';// App
const app = express();
app.get('/', (req, res) => {res.send('Hello world\n');
});app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
In the next steps, we'll look at how you can run this app inside a Docker container using the official Docker image. First, you'll need to build a Docker image of your app.
Creating a Dockerfile
Create an empty file called Dockerfile
:
touch Dockerfile
Open the Dockerfile
in your favorite text editor
The first thing we need to do is define from what image we want to build from. Here we will use the latest LTS (long term support) version carbon
of node
available from the Docker Hub:
FROM node:carbon
Next we create a directory to hold the application code inside the image, this will be the working directory for your application:
# Create app directory
WORKDIR /usr/src/app
This image comes with Node.js and NPM already installed so the next thing we need to do is to install your app dependencies using the npm
binary. Please note that if you are using npm
version 4 or earlier a package-lock.json
file will not be generated.
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./RUN npm install
# If you are building your code for production
# RUN npm install --only=production
Note that, rather than copying the entire working directory, we are only copying the package.json
file. This allows us to take advantage of cached Docker layers. bitJudo has a good explanation of this here.
To bundle your app's source code inside the Docker image, use the COPY
instruction:
# Bundle app source
COPY . .
Your app binds to port 8080
so you'll use the EXPOSE
instruction to have it mapped by the docker
daemon:
EXPOSE 8080
Last but not least, define the command to run your app using CMD
which defines your runtime. Here we will use the basic npm start
which will run node server.js
to start your server:
CMD [ "npm", "start" ]
Your Dockerfile
should now look like this:
FROM node:carbon# Create app directory
WORKDIR /usr/src/app# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./RUN npm install
# If you are building your code for production
# RUN npm install --only=production# Bundle app source
COPY . .EXPOSE 8080
CMD [ "npm", "start" ]
.dockerignore file
Create a .dockerignore
file in the same directory as your Dockerfile
with following content:
node_modules
npm-debug.log
This will prevent your local modules and debug logs from being copied onto your Docker image and possibly overwriting modules installed within your image.
Building your image
Go to the directory that has your Dockerfile
and run the following command to build the Docker image. The -t
flag lets you tag your image so it's easier to find later using the docker images
command:
$ docker build -t <your username>/node-web-app .
Your image will now be listed by Docker:
$ docker images# Example
REPOSITORY TAG ID CREATED
node carbon 1934b0b038d1 5 days ago
<your username>/node-web-app latest d64d3505b0d2 1 minute ago
Run the image
Running your image with -d
runs the container in detached mode, leaving the container running in the background. The -p
flag redirects a public port to a private port inside the container. Run the image you previously built:
$ docker run -p 49160:8080 -d <your username>/node-web-app
Print the output of your app:
# Get container ID
$ docker ps# Print app output
$ docker logs <container id># Example
Running on http://localhost:8080
If you need to go inside the container you can use the exec
command:
# Enter the container
$ docker exec -it <container id> /bin/bash
Test
To test your app, get the port of your app that Docker mapped:
$ docker ps# Example
ID IMAGE COMMAND ... PORTS
ecce33b30ebf <your username>/node-web-app:latest npm start ... 49160->8080
In the example above, Docker mapped the 8080
port inside of the container to the port 49160
on your machine.
Now you can call your app using curl
(install if needed via: sudo apt-get install curl
):
$ curl -i localhost:49160HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 12
ETag: W/"c-M6tWOb/Y57lesdjQuHeB1P/qTV0"
Date: Mon, 13 Nov 2017 20:53:59 GMT
Connection: keep-aliveHello world
We hope this tutorial helped you get up and running a simple Node.js application on Docker.
You can find more information about Docker and Node.js on Docker in the following places:
- Official Node.js Docker Image
- Node.js Docker Best Practices Guide
- Official Docker documentation
- Docker Tag on StackOverflow
- Docker Subreddit
转载于:https://my.oschina.net/u/2306127/blog/1609913
Dockerizing a Node.js web app相关推荐
- node.js 程序_如何不使用外部程序包创建Node.js Web应用程序
node.js 程序 by Abhinav Pandey 通过Abhinav Pandey 如何不使用外部程序包创建Node.js Web应用程序 (How to create a Node.js w ...
- Node.js 指南(Docker化Node.js Web应用程序)
Docker化Node.js Web应用程序 此示例的目的是向你展示如何将Node.js应用程序放入Docker容器中,该指南旨在用于开发,而不用于生产部署,本指南还假设你有一个有效的Docker安装 ...
- node.js Web应用框架Express入门指南
node.js Web应用框架Express入门指南 作者: 字体:[增加 减小] 类型:转载 时间:2014-05-28 我要评论 这篇文章主要介绍了node.js Web应用框架Express入门 ...
- Node.js web应用模块之forever
javascript 一统江湖的势头越来越猛,越来越重的前端,不得不实施前后端分离,angular.js 成功把前端javascript抽象成了一个复杂的MVC框架,注意,它是一个框架,可不是普普通通 ...
- Node.js web应用模块之Supervisor
在开发或调试Node.js应用程序的时候,当你修改js文件后,总是要按下CTRL+C终止程序,然后再重新启动,即使是修改一点小小的参数,也 总是要不断地重复这几个很烦人的操作.这是因为Node.js ...
- Node.js Web开发框架
Node.js非常适用于Web开发,但是现在无论是一个网站,还是Web App都已经成为包括很多不同部分,如前端.数据库.业务模块.功能模块等等的大型项目,使用Node.js从零开始进行Web开发,也 ...
- 18个我最推荐的Node.js Web框架和工具
Node.js是一个底层平台.为了方便开发者的工作变得简单高效,社区诞生了超过上千个库. 随着时间的推移,有很多优秀的库可以供大家选择,下面是不完全选择列表: ExpressExpressExpres ...
- Node.js Web 模块
Node.js Web 模块 什么是 Web 服务器? Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务.它只需支持HTTP协议. ...
- 《Node.js入门》Windows 7下Node.js Web开发环境搭建笔记
最近想尝试一下在IBM Bluemix上使用Node.js创建Web应用程序,所以需要在本地搭建Node.js Web的开发测试环境. 这里讲的是Windows下的搭建方法,使用CentOS 的小伙伴 ...
最新文章
- Vue教程5【vuex】getters,mapState,mapGetters,mapActions,mapMutations,模块化namespace
- 华中科技大学计算机科学卓越班,2016年华中科技大学光电信息科学与工程(卓越计划实验班)专业在江苏录取分数线...
- 波涛汹涌的黄金甲,一碗中药引发的血案!
- itx机箱尺寸_乔思伯发布ITX机箱V8,采用独特抽拉式结构
- elasticsearch _field_stats 源码分析
- HyperLedger Fabric 错误记录
- java holder 遍历_复合组件editableValueHolder与Bean验证不一致
- 数据库和Webapp安全
- UBUNtu·E: 无法获得锁 /var/lib/apt/lists/lock - open (11: 资源暂时不可用) E: 无法对目录 /var/lib/apt/lists/ 加锁 问题解决方法
- 实现让两个DIV横向排列方法揭秘
- Quartus II 12.1安装及破解
- 为什么acdsee服务器怎在运行,ACDSee 启动时报错的解决方法
- 在matlab编辑大于号,教你怎么用MathType编辑大于或小于符号
- 投射电子显微镜(TEM)
- Java+coolq实现QQ机器人
- DataWhale数据分析组队学习——Day2
- 连小白都能看懂的微信开发之测试账号申请
- 前辈做的电子地图API调研,转过来…
- 小伙因家人“催催催” 欲轻生 民警苦劝将其救下
- signature=689995ceebd2e64b214c3148d7b8e47a,WDR34基因突变致窒息性胸廓发育不良1例报道并文献复习...
热门文章
- python北京理工大学推荐的书-Python教程书籍(北理工第2版)思考练习-第三章
- python创建打开文件-Python文件处理:创建、打开、追加、
- 初学python还是swift-请问零基础学习python 和swift哪个更好入门呢?
- python用途与前景-java和Python的前景谁更好
- python基础包括什么-Python基础教程 模块包含什么
- java文件名与class关系
- 排球计分程序(八)——验证编辑方法(Edit method)和编辑视图(Edit view)
- 依赖ConstraintLayout报错,Could not find *****,Failed to resolve:*****
- css中margin-top/margin-bottom失效
- AMD正式公布第七代桌面级APU AM4新接口