Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用Docker部署Node应用 #9

Closed
Vibing opened this issue Jun 18, 2019 · 3 comments
Closed

使用Docker部署Node应用 #9

Vibing opened this issue Jun 18, 2019 · 3 comments

Comments

@Vibing
Copy link
Owner

Vibing commented Jun 18, 2019

上篇《前端也要学Docker啊!》介绍了Docker及它的三个主要概念:Image(镜像)、Container
(容器)、Registry(仓库) 以及Docker安装。

本篇我们来动手实践:在本地创建一个自己的镜像(Node应用),使用该镜像创建容器并执行容器中的Node应用。

创建一个Node项目

在根目录创建index.js

//index.js
const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello Docker O(∩_∩)O~~';
});

app.listen(3000);

创建 Docker 镜像需要用到 docker build命令,而docker build命令又是根据 Dockerfile 配置文件来构建镜像,所以我们要在项目根目录创建一个 Dockerfile 文件:

#Dockerfile
FROM node:10.13-alpine #项目的基础依赖
MAINTAINER chenLong #项目维护者
COPY . . #将本机根目录所有文件拷贝到容器的根目录下 这个可以根据喜好调节路径
EXPOSE 3000 #容器对外暴露的端口
RUN npm i #安装node依赖
CMD npm start #在容器环境里执行的命令

你可以到 Docker 官网查看详细的Dockfile说明

构建镜像

上面 Node 代码已经完成了,我们使用 yarn init -ynpm init -y 完成package.json初始化,然后安装一个koa依赖:执行yarn add koanpm i koa

然后我们在本地跑一下 node 程序:node index.js,打开浏览器输入 localhost:3000 ,可以看到浏览器中成功显示了 Hello Docker O(∩_∩)O~~ 。

WX20190618-140213

程序没问题,我们开始构建这个镜像,执行命令:docker build -t docker-demo/hello-docker:v1 . (注意最后有个 "." 是必须的)

  • -t: --tag简写,镜像的名字及标签,通常 name:tag 或者 name 格式;可以在一次构建中为一个镜像设置多个标签。

上面的 docker-demo/hello-docker是我们定义的镜像名称,v1是标签名称(类似版本号)

WX20190618-121212@2x

图中蓝色框表示 Dockerfile 的执行步骤。此时一个名为docker-demo/hello-docker的镜像已经创建完成了,现在我们执行docker images查看一下:

WX20190618-112816@2x

表示本地的镜像列表中已经有了我们刚才创建的docker-demo/hello-docker

让Node程序在Docker中跑起来

上面已经创建好了镜像,里面包含着我们写的代码,现在我们需要把代码运行起来。
非常简单,我们使用docker run命令使用镜像创建一个容器实例(此刻脑海中浮现 var p1 = new Person() )。

我们执行命令: docker run -i -t -p 8080:3000 docker-demo/hello-docker:v1

  • -i: 以交互模式运行容器,通常与 -t 同时使用;
  • -t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用;
  • -p: 指定端口映射,格式为:主机(宿主)端口:容器端口,这里将容器的3000端口与宿主机的8080端口映射

WX20190618-121238@2x

打开浏览器,运行localhost:8080:
WX20190618-121254

完美,容器里的代码已经跑起来了!

总结

  1. 在项目根目录创建 Dockerfile 并配置
  2. 使用 docker build 命令创建Docker镜像,该命令会根据 Dockerfile 里的配置来构建镜像
  3. 使用 docker run 命令根据镜像创建对应的容器实例并运行
@ibule
Copy link

ibule commented Jul 27, 2023

有没有前端快速学Java 和 sprin boot的文章

@Vibing
Copy link
Owner Author

Vibing commented Aug 3, 2023

有没有前端快速学Java 和 sprin boot的文章

建议买视频课,一个项目做下来就入门了

@ibule
Copy link

ibule commented Aug 15, 2023

你买了吗 ?哈哈 推荐个

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants