在 Docker 中使用 Nginx 镜像部署前端项目的步骤如下:
1. 准备 Nginx 镜像
在装好有网络的环境中,先拉取所需的镜像并保存为nginx.tar文件
docker pull nginx # 拉取最新的镜像
docker save -o nginx.tar nginx
2. 打包前端项目
确保前端项目已经打包完成(例如使用 npm run build 或 yarn build),通常在 dist 或 build 目录中。
3. 创建 nginx.conf 配置文件,复制以下内容
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html; # 重要,否则路由跳转有问题
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
4. 传输文件到 Linux 离线环境
将 nignx.tar镜像文件、dist打包文件、nginx.conf配置文件 传输到 Linux 离线环境
5. 在离线环境中加载 Nignx 镜像
docker load -i nignx.tar
6. 运行 Nignx 容器
docker run -d -p 80:80 \
-v /path/to/your/dist:/usr/share/nginx/html \
-v /path/to/your/nginx.conf:/etc/nginx/conf.d/default.conf \
nginx
在浏览器中访问 http://localhost