一、准备工作
-
服务器环境
-
安装 Docker 和 Docker Compose:
bash# 安装 Docker curl -fsSL https://get.docker.com | sh systemctl start docker systemctl enable docker # 安装 Docker Compose sudo curl -L "https://github.com/docker/compose/releases/download/v2.23.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose
-
-
项目结构
/project ├── backend/ # Node.js 后端 │ ├── Dockerfile │ ├── package.json │ └── src/ ├── frontend/ # 前端项目 │ ├── Dockerfile │ ├── package.json │ └── public/ └── docker-compose.yml # 编排文件
二、部署 Node.js 后端服务
1. 编写 Dockerfile
dockerfile
# backend/Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000 # 根据实际端口修改
CMD ["npm", "start"] # 或 "node server.js"
2. 构建镜像
bash
cd backend
docker build -t node-backend .
3. 验证运行
bash
docker run -d -p 3000:3000 --name my-node-app node-backend
三、部署前端项目(以 React 为例)
1. 编写 Dockerfile
dockerfile
# frontend/Dockerfile
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build # 生成静态文件到 /app/dist
# 使用 Nginx 托管
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
2. 构建镜像
bash
cd frontend
docker build -t react-frontend .
3. 验证运行
bash
docker run -d -p 80:80 --name my-react-app react-frontend
四、使用 Docker Compose 编排
1. 编写 docker-compose.yml
yaml
version: '3.8'
services:
backend:
build: ./backend
ports:
- "3000:3000"
environment:
- NODE_ENV=production
restart: unless-stopped
frontend:
build: ./frontend
ports:
- "80:80"
depends_on:
- backend
restart: unless-stopped
2. 启动所有服务
bash
docker-compose up -d # 后台运行
3. 常用命令
bash
docker-compose logs # 查看日志
docker-compose down # 停止服务
docker-compose restart # 重启服务
五、进阶配置
1. 使用 .env
管理环境变量
-
在
docker-compose.yml
中引用:yamlenvironment: - DB_HOST=${DB_HOST}
-
创建
.env
文件:DB_HOST=mysql
2. 数据库服务(如 MySQL)
yaml
services:
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: rootpass
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
3. Nginx 反向代理(可选)
nginx
server {
listen 80;
server_name your-domain.com;
location /api {
proxy_pass http://backend:3000;
}
location / {
proxy_pass http://frontend;
}
}
六、访问服务
- 前端:
http://服务器IP
- 后端 API:
http://服务器IP:3000/api
常见问题
-
端口冲突
- 确保服务器防火墙开放端口(如 80、3000)。
-
文件权限问题
-
在 Dockerfile 中添加用户权限管理:
dockerfileRUN chown -R node:node /app USER node
-
-
构建缓存优化
- 将
COPY package.json
和RUN npm install
提前,利用 Docker 缓存。
- 将
通过以上步骤,你可以快速在服务器上部署全栈项目。实际应用中,可根据需求扩展数据库、负载均衡等配置。