Docker化你的Node应用程序
欢迎回来!本文是 Dockerize 系列文章的一部分,请务必阅读简介部分,我会在其中介绍一些我们将要用到的概念。
今天,我们将对我们的 Node 应用程序进行 docker 化,这与上一部分中我们通过利用具有多阶段构建的构建器模式对我们的 React 应用程序进行 docker 化的方式非常相似!
我还制作了一个视频,如果你想跟着看的话
项目设置
我已经初始化了一个简单的快速应用程序
├── node_modules
├── index.js
├── package.json
└── yarn.lock
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
app.get('/', (request, response) => {
response.status(200).json({
message: 'Hello Docker!',
});
});
app.listen(PORT, () => {
console.log(`Server is up on localhost:${PORT}`);
});
我还设置了esbuild来捆绑我们的项目。
"build": "esbuild --bundle src/index.js --outfile=build/app.js --minify --platform=node"
有关更多详细信息,您可以查看我之前的文章使用 Webpack 和 ESBuild 实现快速 TypeScript。
为了发展
让我们首先添加一个Dockerfile
FROM node:14-alpine AS development
ENV NODE_ENV development
# Add a work directory
WORKDIR /app
# Cache and Install dependencies
COPY package.json .
COPY yarn.lock .
RUN yarn install
# Copy app files
COPY . .
# Expose port
EXPOSE 4000
# Start the app
CMD [ "yarn", "start" ]
让我们创建一个docker-compose.dev.yml
。在这里,我们还将代码挂载到卷中,以便在开发时将更改与容器同步。
version: "3.8"
services:
app:
container_name: app-dev
image: app-dev
build:
context: .
target: development
volumes:
- ./src:/app/src
ports:
- 4000:4000
让我们更新package.json
脚本
"dev": "docker-compose -f docker-compose.dev.yml up"
我们可以使用该-d
标志以守护进程模式运行
让我们开始开发吧!
yarn dev
太好了,我们的开发服务器已启动!
Attaching to app-dev
app-dev | yarn run v1.22.5
app-dev | $ nodemon src/index.js
app-dev | [nodemon] to restart at any time, enter `rs`
app-dev | [nodemon] watching path(s): *.*
app-dev | [nodemon] starting `node src/index.js`
app-dev | Server is up on localhost:4000
用于生产
FROM node:14-alpine AS builder
ENV NODE_ENV production
# Add a work directory
WORKDIR /app
# Cache and Install dependencies
COPY package.json .
COPY yarn.lock .
RUN yarn install --production
# Copy app files
COPY . .
# Build
CMD yarn build
FROM node:14-alpine AS production
# Copy built assets/bundle from the builder
COPY --from=builder /app/build .
EXPOSE 80
# Start the app
CMD node app.js
让我们添加一个docker-compose.prod.yml
用于生产
version: "3.8"
services:
app:
container_name: app-prod
image: app-prod
build:
context: .
target: production
docker-compose -f docker-compose.prod.yml build
让我们在端口上启动我们的生产容器,80
名称为react-app
docker run -p 80:4000 --name node-app app-prod
后续步骤Next steps
这样,我们应该能够在工作流程中利用 docker,并将生产镜像更快地部署到我们选择的任何平台。
如果您遇到任何问题,请随时通过Twitter与我联系。
文章来源:https://dev.to/karanpratapsingh/dockerize-node-application-222k