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.js 应用 #60

Open
lmk123 opened this issue Mar 19, 2018 · 0 comments
Open

在 Docker 中运行 Node.js 应用 #60

lmk123 opened this issue Mar 19, 2018 · 0 comments

Comments

@lmk123
Copy link
Owner

lmk123 commented Mar 19, 2018

最近开发一个 Node.js 应用时初次接触到了 Docker,用到了不少 Docker 的命令,这里记录一下方便自己查看。

这篇文章不会详细解释每个命令是做什么的,权当作一个入门 Docker 的提纲吧。

假设我们有一个如下几行代码的 Node.js 应用:

require('http')
  .createServer((req, res) => {
    res.end('hello docker')
  })
  .listen(8080)

一、编写 Dockerfile

首先,将应用部署在 Docker 中的第一步就是为它编写一个 Dockerfile

FROM node
WORKDIR /app
COPY . ./
EXPOSE 8080
ENTRYPOINT ["node", "index.js"]

提问:CMDENTRYPOINT 有什么不同?

二、编译镜像

使用 docker build(等同于 docker image build)编译一个镜像:

$ docker build -t simple-node-app .

运行 docker images(等同于 docker image list)可以查看所有镜像:

$ docker images
REPOSITORY                                TAG                         IMAGE ID            CREATED             SIZE
simple-node-app                           latest                      93bbb19457f2        18 seconds ago      673MB
node                                      latest                      ec70562ad6f0        3 days ago          673MB

三、运行容器

使用 docker run(等同于 docker container run)运行容器:

$ docker run --rm -it -p 9090:8080 simple-node-app

提问:--rm-it-p 的作用?

现在打开 http://localhost:9090 就能看到 hello docker 了。

使用 docker ps(等同于 docker container ls)查看运行中的容器:

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
0ba262d81a87        simple-node-app     "node index.js"     4 minutes ago       Up 4 minutes        0.0.0.0:9090->8080/tcp   adoring_volhard

添加 -a 参数就能看到停止的容器了。

运行 lsof -nP -iTCP -sTCP:LISTEN 查看端口占用情况:

$ lsof -nP -iTCP -sTCP:LISTEN
COMMAND     PID      USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
vpnkit    57981 limingkai   21u  IPv4 0x1bddb238e701fcc9      0t0  TCP *:9090 (LISTEN)
vpnkit    57981 limingkai   22u  IPv6 0x1bddb238e768a4a1      0t0  TCP [::1]:9090 (LISTEN)

四、查看容器运行状态

进入容器的 shell:

$ docker exec -it 0ba262d81a87 /bin/bash
root@0ba262d81a87:/app#

查看运行中的 Node.js 进程:

# ps -aux | grep node
root         1  0.0  1.4 876240 29952 pts/0    Ssl+ 18:14   0:00 node index.js
root        17  0.0  0.0    508     4 pts/1    R+   18:22   0:00 grep node

退出容器的 shell:

# exit

五、停止容器

使用 docker stop(等同于 docker container stop)停止容器。

$ docker stop 0ba262d81a87
0ba262d81a87

提问:可以在运行容器命令窗口使用 Ctrl + C 停止容器吗?如果不可以,为什么?

推荐文档

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

No branches or pull requests

1 participant