准备工作
确保服务器已安装Docker和Docker Compose。Docker的安装方法因操作系统而异,以下以Ubuntu为例:
sudo apt update
sudo apt install docker.io docker-compose
验证安装是否成功:
docker --version
docker-compose --version
项目结构
假设前端项目基于React或Vue等框架构建,已通过npm run build生成静态文件(通常位于dist或build目录)。项目结构示例如下:
/my-frontend
├── Dockerfile
├── docker-compose.yml
├── /dist
└── /nginx-conf
└── default.conf
编写Dockerfile
创建Dockerfile文件,选择Nginx作为服务器托管静态文件:
# 使用官方Nginx镜像作为基础
FROM nginx:alpine
# 删除默认配置文件
RUN rm /etc/nginx/conf.d/default.conf
# 复制自定义Nginx配置
COPY nginx-conf/default.conf /etc/nginx/conf.d/
# 将构建好的前端文件复制到Nginx服务目录
COPY dist /usr/share/nginx/html
# 暴露80端口
EXPOSE 80
# 启动Nginx服务
CMD ["nginx", "-g", "daemon off;"]
配置Nginx
在nginx-conf/default.conf中配置Nginx以正确处理前端路由(如React Router或Vue Router):
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html;
}
# 可选:配置API代理
location /api {
proxy_pass http://backend-service:5000

被折叠的 条评论
为什么被折叠?



