部署单页应用(SPA)使用Docker和Nginx是一个高效且可扩展的方案。以下是详细步骤:
首先确保你的单页应用已经构建完成,通常会有以下结构:
dist/
├── index.html
├── static/
│ ├── js/
│ ├── css/
│ └── images/
在项目根目录创建Dockerfile
:
# 使用官方Nginx镜像作为基础
FROM nginx:alpine
# 删除默认的Nginx配置
RUN rm -rf /etc/nginx/conf.d/*
# 将构建好的SPA文件复制到Nginx的默认目录
COPY dist/ /usr/share/nginx/html
# 复制自定义的Nginx配置
COPY nginx.conf /etc/nginx/conf.d/default.conf
# 暴露80端口
EXPOSE 80
# 启动Nginx
CMD ["nginx", "-g", "daemon off;"]
创建nginx.conf
文件:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存设置
location ~* \.(?:css|js|jpg|jpeg|gif|png|ico|svg)$ {
expires 1y;
add_header Cache-Control "public";
}
# 禁用favicon.ico日志
location = /favicon.ico {
log_not_found off;
access_log off;
}
}
在项目根目录运行:
docker build -t spa-app .
docker run -d -p 8080:80 --name my-spa-app spa-app
打开浏览器访问 http://localhost:8080
可以创建不同的Nginx配置文件用于不同环境:
# 根据构建参数选择配置文件
ARG ENV=production
COPY nginx.${ENV}.conf /etc/nginx/conf.d/default.conf
构建时指定环境:
docker build --build-arg ENV=staging -t spa-app .
如果需要在Docker中构建应用:
# 构建阶段
FROM node:alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# 生产阶段
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
确保Nginx配置正确处理前端路由:
location / {
try_files $uri $uri/ /index.html;
}
# 启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 静态资源缓存
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
expires 1y;
add_header Cache-Control "public";
access_log off;
}
404错误:
try_files $uri $uri/ /index.html;
跨域问题:
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
容器启动失败:
docker exec -it my-spa-app nginx -t
docker logs my-spa-app
通过以上步骤,你可以轻松地将单页应用部署在Docker容器中,并使用Nginx作为高性能的Web服务器。