Node.js 应用程序
创建一个目录来存放你的项目文件,然后在该目录下创建以下文件。
- package.json
{
"name": "docker-node-test",
"version": "1.0.0",
"description": "A simple Node.js app for Docker multi-stage build testing",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.17.1"
}
}
- index.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Dockerfile (多阶段构建)
# Stage 1: Build the application
FROM node:14 AS builder
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package*.json ./
RUN npm install
# Copy app source code
COPY . .
# Build the application (if needed)
# RUN npm run build
# Stage 2: Run the application
FROM node:14-alpine
# Create app directory
WORKDIR /usr/src/app
# Copy only the necessary files from the builder stage
COPY --from=builder /usr/src/app .
# Expose the port the app runs on
EXPOSE 3000
# Start the app
CMD ["npm", "start"]
使用说明
创建项目目录和文件:
创建一个新的目录,并在其中创建上述package.json
和index.js
文件。创建Dockerfile:
在同一目录中创建Dockerfile
文件,并将上述内容复制进去。构建Docker镜像:
在终端中导航到该目录并运行以下命令:docker build -t docker-node-test .
运行Docker容器:
运行以下命令来启动容器:docker run -p 3000:3000 docker-node-test
测试应用:
在浏览器中访问http://localhost:3000
,你应该会看到"Hello, World!"。
通过这种多阶段构建,你可以减少最终镜像的大小,仅包含运行应用所需的文件。