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!"。
通過這種多階段構建,你可以減少最終鏡像的大小,僅包含運行應用所需的文件。