Docker多阶段构建Node.js应用程序

发布于:2024-07-06 ⋅ 阅读:(47) ⋅ 点赞:(0)

Node.js 应用程序

创建一个目录来存放你的项目文件,然后在该目录下创建以下文件。

  1. 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"
  }
}
  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"]

使用说明

  1. 创建项目目录和文件
    创建一个新的目录,并在其中创建上述package.jsonindex.js文件。

  2. 创建Dockerfile
    在同一目录中创建Dockerfile文件,并将上述内容复制进去。

  3. 构建Docker镜像
    在终端中导航到该目录并运行以下命令:

    docker build -t docker-node-test .
    
  4. 运行Docker容器
    运行以下命令来启动容器:

    docker run -p 3000:3000 docker-node-test
    
  5. 测试应用
    在浏览器中访问http://localhost:3000,你应该会看到"Hello, World!"。

通过这种多阶段构建,你可以减少最终镜像的大小,仅包含运行应用所需的文件。


网站公告

今日签到

点亮在社区的每一天
去签到