Dockerfile nodejs容器搭建
文章目录一、Dockerfile编写二、nodejs服务器三、新建文件四、构建镜像一、Dockerfile编写FROM node:12-alpine# Create app directoryWORKDIR /usr/src/app# Install app dependencies# A wildcard is used to ensure both package.json AND packa
·
一、Dockerfile编写
FROM node:12-alpine
# 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 ci --only=production
# Bundle app source
COPY . .
Volume /root/nodejsdocker_alpine/
EXPOSE 8081
CMD [ "node", "server.js" ]
二、nodejs服务器
server.js
const express = require('express');
// Constants
const PORT = 8081;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/api', (req, res) => {
res.send('Hello World');
});
app.get('/api/test', (req, res) => {
res.send('Hello World api/test');
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
三、新建文件
package.json
{
"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"
}
}
.dockerignore
这将避免你的本地模块以及调试日志被拷贝进入到你的 Docker 镜像中,以至于把你镜像原有安装的模块给覆盖了。
node_modules
npm-debug.log
四、构建镜像
开关符 -t
让你标记你的镜像,以至于让你以后很容易地用 docker images
找到它。
docker build -t nodejs_alpine .
构建完成:
[root@iZ2ze5ot8cnsficuqqnoj5Z ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nodejs_alpine latest b56a8ee0393f 46 seconds ago 92.2MB
运行:
[root@iZ2ze5ot8cnsficuqqnoj5Z ~]# docker run -it --name nodejs -p 8081:8081 b56a8ee0393f
Running on http://0.0.0.0:8081
在宿主机上访问:
[root@iZ2ze5ot8cnsficuqqnoj5Z ~]# curl localhost:8081/api
Hello World
进入容器内部:
[root@iZ2ze5ot8cnsficuqqnoj5Z ~]# docker exec -it eb1865104671 sh
进步ing
更多推荐
已为社区贡献3条内容
所有评论(0)